这听起来很容易,但我不能让它工作。我想从下面的示例代码中访问属性dataSource
(我可以用例如print(A.data)
获得第一个属性,但我想从同一类的第二个函数中获得一个:
class myclass():
def __init__(self):
self.data = [1,2,3]
self.other_data = [4,5,6]
def other(self):
self.dataSource = 'i want this string'
A = myclass()
print(A.dataSource)
Tags:
必须首先调用
other
方法,因为这是创建实例的datasource
属性的地方:然后您可以通过以下方式访问它:
或者,回答您的评论,如果您想使用
getattr
:您尚未创建属性
dataSource
,因此无法访问它。如果总是希望类型为myclass
的对象具有该属性,请在__init__
函数中创建它。你知道吗或者,先调用
A.other()
函数,然后尝试打印A.dataSource
您需要调用
A.other()
方法:相关问题 更多 >
编程相关推荐