Skip to main content
 首页 » 编程设计

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

2025年05月04日16pengyingh

这听起来很简单,但我做不到。我想从以下示例代码访问属性 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) 

请您参考如下方法:

您还没有创建属性dataSource,所以您不能访问它。如果您始终希望 myclass 类型的对象具有该属性,请在 __init__ 函数中创建它。

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