I'm new to OOP, but I'm trying to look at an object's vars. Other Stack-O answers have suggested using object.__dict__
or vars(object)
. So I went into the Python shell to try a quick example, but I noticed neither of these answers prints the object's default attributes, only newly-assigned attributes, e.g.:
>>> class Classy():
... inty = 3
... stringy = "whatevs"
...
>>> object = Classy()
>>> object.inty
3
>>> object.__dict__
{}
>>> vars(object)
{}
>>> object.inty = 27
>>> vars(object)
{'inty': 27}
>>> object.__dict__
{'inty': 27}
Why are the variables present in one sense but not another? Is it because I didn't explicitly initialize them or something?
You can use
vars
or__dict__
with the class name, not instance:Option 1:
Output:
Option 2:
It's important understanding that in Python everything is an object (including functions, and a
class
declaration itself)When you do this:
You're assigning
inty
andstringy
to theClass
, not to the instances. Check this:Wait... A
class
with a__dict__
? Yeah, becauseClassy
is also an instance (of typeclassobj
, since you're using old style classes, which you shouldn't really do, by the way... You should inherit fromobject
, which gives you access to more goodies)Now, if you created an instance of classy, and put an
inty
value to it, you would have:Which outputs
See the
inty
being 5 in the__dict__
of the instance but still being 3 in the__dict__
of the class? It's because now you have twointy
: One attached toclassy
, an instance of the classClassy
and another one attached to the classClassy
itself (which is, in turn, an instance ofclassobj
)If you did
You'd see:
Why? Because when you try to get
inty
on the instance, Python will look for it in the__dict__
of the instance first. If it doesn't find it, it will go to the__dict__
of the class. That is what's happening onclassy.stringy
. Is it in theclassy
instance? Nopes. Is it in theClassy
class? Yep! Aight, return that one... And that's the one you see.Also, I mentioned that the Classy class is an object, right? And as such, you can assign it to something else like this:
And you'll see the
5
that was "attached" inClassy.__init__
because when you didWhat = Classy
, you're assigning theclass Classy
to a variable namedWhat
, and when you dofoo=What()
you're actually running the constructor ofClassy
(remember:What
andClassy
are the same thing)Another thing Python allows (and that I personally don't like because then it makes code very difficult to follow) is attaching attributes to instances "on-the-fly":
Will output
Oh, and did I say that functions are objects? Yeah, they are... and as such, you can also assign attributes to them (also, something that makes code really, really confusing) but you could do it...
Outputs:
The reason that the
.__dict__
andvars
methods aren't working as you expected is because you haven't defined a constructor for your class with python'sself
reference. The following will do what you're looking for:Outputs:
Cheers!