简体   繁体   中英

How to access attribute of second or other definition from the same class in Python

This sounds easy but I cannot get it working. I would like to access the attribute dataSource from the following sample code (I can get the first ones with eg print(A.data) just fine but I want the one from the second function from the same class:

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)

You haven't created the attribute dataSource yet, so you can't access it. If you always want an object of type myclass to have that attribute, create it in the __init__ function.

Alternately, call the A.other() function first, then try printing A.dataSource

You have to call your other method first, as this is where you create the datasource attribute of your instance:

a = myclass()
a.other()

Then you can access it by:

print(a.dataSource)

Or, to answer your comment, if you want to use getattr :

print(getattr(a, 'dataSource'))

You need to call A.other() method:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM