类结构中的变量初始化

时间:2016-12-27 22:28:04

标签: python class variables

我正在尝试在init中初始化一个函数/方法。 所以A类中的self.y返回10的正确值。或者在A?

中使用方法get_y

请参阅以下代码和评论。感谢

class A(object):
    def __init__(self):
        self.x = 5
        self.y = None
        # self.y = B.eval(self)?? # wants y to be a value obtained from B.eval()
    def get_x(self):
        return self.x

    def get_y(self):
        # wants y to be a value obtained from B.eval()
        #return B.eval(self) ??

class B(object):
    def eval(ClassA):
        """
        :param ClassA: is an instance of A
        :return: value
        """
        return ClassA.get_x() + 5


a = A()
b = B()
print(a.get_y()) # wants value 10 printed out here
print(B.eval(a))

1 个答案:

答案 0 :(得分:0)

B.eval() classmethod作为class B中的方法装饰器使用,如下所示:

class A(object):
    def __init__(self):
        self.x = 5
        self.y = None
        self.y = B.eval(self)
    def get_x(self):
        return self.x

    def get_y(self):
        return B.eval(self)

class B(object):
    @staticmethod    # ADD THIS LINE
    def eval(ClassA):
        """
        :param ClassA: is an instance of A
        :return: value
        """
        return ClassA.get_x() + 5

a = A()
b = B()
print(a.get_y())  # -> 10
print(B.eval(a))  # -> 10