I need to access list of class members in class methods specifically in __init__()
function with intention of initializing them en masse. I tried to use __dict__
and vars(self)
but Unfortunately they return empty dict
object, unless using direct initialization such as self.y=5
. The questions are; why that is empty and how can I initialize them at once, or essentially is variable __dict__
suitable for bulk initialization?
thank you
sample code is like this:
class P:
def __init__(self):
print("inside __init__() :",self.y,self.__dict__)
x=8
y=9
p=P()
print(" y is: ", p.y)
print("and __dict__ is:",p.__dict__)
output:
inside __init__() : 9 {}
y is: 9
and __dict__ is: {}
- Python version: 3.8.5
- Tested Operating systems: windows 10, MacOS 10.15.7 and Linux CentOS 7
2
Answers
__dict__
only holds instance attributes.x
andy
in your examples are class attributes.self.x
is an expression that could mean many different things; the actual result depends on which lookup succeeds first.When you make an assignment like
self.x = 5
, then the value5
is associated with the keyx
inself.__dict__
.When you try to get the value of
self.x
, the first thing that is tried isself.__dict__['x']
. If that fails, though, it triesP.x
. If that failed, it would check forx
as an attribute in each ancestor ofP
in the MRO, until a value is found. If nothing is found, anAttributeError
is raised. (This ignores the use of__getattr__
or__getattribute__
, but is sufficient to explain howself.x
can provide a value whenself.__dict__
is empty.)Python class instances are dynamic – they don’t have variables until you put them there (see note below). And they don’t have any pre-knowledge of what those variables should be. Usually that’s done by adding them one by one (e.g.,
self.foo = 1
) in__init__
or other methods in the class. But if you have a different source of variables, you can do it by adding toself.__dict__
. Suppose I have a row from a CSV file and I want a class that is initialized by that row. I could doOutputs
There are other ways to initialize, of course. It depends on what the source of your "en mass" data is.
If you want to add all of the keyword arguments you could
(Note: You can use
__slot__
to predefine variables in a class. These bypass the instance dict)