在Python中如何从同一类中访问第二个或其他定义的属性

2024-04-20 12:50:16 发布

您现在位置:Python中文网/ 问答频道 /正文

这听起来很容易,但我不能让它工作。我想从下面的示例代码中访问属性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: 函数代码self示例data属性initdef
3条回答

必须首先调用other方法,因为这是创建实例的datasource属性的地方:

a = myclass()
a.other()

然后您可以通过以下方式访问它:

print(a.dataSource)

或者,回答您的评论,如果您想使用getattr

print(getattr(a, 'dataSource'))

您尚未创建属性dataSource,因此无法访问它。如果总是希望类型为myclass的对象具有该属性,请在__init__函数中创建它。你知道吗

或者,先调用A.other()函数,然后尝试打印A.dataSource

您需要调用A.other()方法:

>>> a.other()
>>> a.dataSource
'i want this string'

相关问题 更多 >