我可以在python

时间:2016-10-13 08:21:42

标签: python python-2.7 python-3.x

我有一个名为BaseClass的课程

class BaseClass(object):
    def __init__(self, context):
        self.context = context

我有一些其他类派生自基类,如

BaseSubClass(object):
    def __init__(self, context=None):
        self.context = context

    def method1(self):
        """"Do stuff here """

    def method2(self):
        """"Do stuff here """

    def method3(self):
        """"Do stuff here """

然后我有一些类sub classes of BaseSubClass

class Class1(BaseSubClass):

    def get_something(self):
         """Perform some actions here on the basis of the context passed in self"""
        context = self.context
        return 'abcd'

    @property
    def data(self):
        return self.get_something()

class Class2(BaseSubClass):

    def get_something(self):
         """Perform some actions here on the basis of the context passed in self"""
        context = self.context
        return 'abcdewewew'

    @property
    def data(self):
        return self.get_something()



class Class3(BaseSubClass):

    def get_something(self):
         """Perform some actions here on the basis of the context passed in self"""
        context = self.context
        return 1221212

    @property
    def data(self):
        return self.get_something()

最后我要做的是

class MainClass(BaseClass):
    c1 = Class1()
    c2 = Class2()
    c3 = Class3()

我想做的是。当我创建BaseClass对象时,不知何故我想将context变量传递给它属性类,即c1,c2,c3,这样当我访问该实例的属性时,我将获得计算数据在第一次。喜欢

obj = MainClass(context)
obj.c1.data    # at this time it should return the actual data which will be depend on the context variable.

如果我将属性用作proerty,这是可能的。喜欢

@property
def c1(self):
    return Class1(context=self.context).data

@property
def c2(self):
    return Class2(context=self.context).data

但是我想知道如果我可以将包装类变量传递给我在这个包装类中实例化的类。

0 个答案:

没有答案