我正在尝试在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))
答案 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