Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
406 views
in Technique[技术] by (71.8m points)

methods - How to get instance variables in Python?

Is there a built-in method in Python to get an array of all a class' instance variables? For example, if I have this code:

class hi:
  def __init__(self):
    self.ii = "foo"
    self.kk = "bar"

Is there a way for me to do this:

>>> mystery_method(hi)
["ii", "kk"]

Edit: I originally had asked for class variables erroneously.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Every object has a __dict__ variable containing all the variables and its values in it.

Try this

>>> hi_obj = hi()
>>> hi_obj.__dict__.keys()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...