1

私はこのようなことをしたいと思います:

class A:
    def hello(): print "Hello"

# I do not want to explicitly setup a:
a = A()

# a = A() -> I want this to happen automatically when I access a
# My first try is this:
def a():
    return A()

# Also, I do not want to call a as a function a(): it must be an object
# And it must stay alive and initialized
a.hello() # a is created, as object of class A
a.hello() # I do not want a second instantiation

どうすればこれを実装できますか? properties? cached-properties? これらはクラス専用です。 a はモジュールレベルのオブジェクトです。

4

3 に答える 3

3

多分このようなもの:

class A(object):
    def hello(self):
        print "Hello"

class LazyA(object):
    def __init__(self):
        self.instance = None

    def __getattr__(self, k):
        if self.instance is None:
            self.instance = A()

        return getattr(self.instance, k)

a = LazyA()
于 2013-04-25T10:15:23.877 に答える
0

Pavelによる答えの一般化:

class LazyClass(object):

    def __init__(self, myclass, *args, **kwargs):
        self.instance = None
        self.myclass = myclass
        self.args = args
        self.kwargs = kwargs

    def __getattr__(self, k):
        if self.instance is None:
            self.instance = self.myclass(*self.args, **self.kwargs)

        return getattr(self.instance, k)

class A(object):

    def __init__ (self, name):
        self.name = name
        print "Created"

    def hello(self):
        print "Hello " + self.name

import unittest
class TestLazyClass(unittest.TestCase):

    def setUp(self):
        self.a = LazyClass(A, 'Daniel')

    def test_it(self):
        self.a.hello()
        self.a.hello()
于 2013-04-25T10:40:19.140 に答える