>>> class new_class():
... def __init__(self, number):
... self.multi = int(number) * 2
... self.str = str(number)
...
>>> a = new_class(2)
>>> a.__dict__
{'multi': 4, 'str': '2'}
>>> a.__dict__.keys()
dict_keys(['multi', 'str'])
You may also find pprint helpful.
Answer from Roger Pate on Stack Overflow>>> class new_class():
... def __init__(self, number):
... self.multi = int(number) * 2
... self.str = str(number)
...
>>> a = new_class(2)
>>> a.__dict__
{'multi': 4, 'str': '2'}
>>> a.__dict__.keys()
dict_keys(['multi', 'str'])
You may also find pprint helpful.
dir(instance)
# or (same value)
instance.__dir__()
# or
instance.__dict__
Then you can test what type is with type() or if is a method with callable().
I'm using the plex python library to get some info from my plex server.
What I wanted to get was the path of a movie.
I tried to use dir(movie_object), vars(movie_object), and movie_object.__dict__ to try and find all of the movie attributes, and to see where the path was stored.
But there was no attribute that contained the file path information.
In the end I found it under movie_object.location by inspecting the object in the VSCode debugging tools.
Why does VSCode show the location attribute, but dir, vars, or __dict__ do not show it?
Is there a way to reliably get ALL of an objects attributes in python?
introspection - Get all object attributes in Python? - Stack Overflow
python - Get an object attribute - Stack Overflow
Accessing attributes of a class
python - How to access (get or set) object attribute given string corresponding to name of that attribute - Stack Overflow
Videos
Use the built-in function dir().
I use __dict__ and dir(<instance>)
Example:
class MyObj(object):
def __init__(self):
self.name = 'Chuck Norris'
self.phone = '+6661'
obj = MyObj()
print(obj.__dict__)
print(dir(obj))
# Output:
# obj.__dict__ --> {'phone': '+6661', 'name': 'Chuck Norris'}
#
# dir(obj) --> ['__class__', '__delattr__', '__dict__', '__doc__',
# '__format__', '__getattribute__', '__hash__',
# '__init__', '__module__', '__new__', '__reduce__',
# '__reduce_ex__', '__repr__', '__setattr__',
# '__sizeof__', '__str__', '__subclasshook__',
# '__weakref__', 'name', 'phone']
To access field or method of an object use dot .:
user = User()
print user.fullName
If a name of the field will be defined at run time, use buildin getattr function:
field_name = "fullName"
print getattr(user, field_name) # prints content of user.fullName
Use getattr if you have an attribute in string form:
>>> class User(object):
name = 'John'
>>> u = User()
>>> param = 'name'
>>> getattr(u, param)
'John'
Otherwise use the dot .:
>>> class User(object):
name = 'John'
>>> u = User()
>>> u.name
'John'
There are built-in functions called getattr and setattr
getattr(object, attrname)
setattr(object, attrname, value)
In this case
x = getattr(t, 'attr1')
setattr(t, 'attr1', 21)
If you want to keep the logic hidden inside the class, you may prefer to use a generalized getter method like so:
class Test:
def __init__(self):
self.attr1 = 1
self.attr2 = 2
def get(self,varname):
return getattr(self,varname)
t = Test()
x = "attr1"
print ("Attribute value of {0} is {1}".format(x, t.get(x)))
Outputs:
Attribute value of attr1 is 1
Another apporach that could hide it even better would be using the magic method __getattribute__, but I kept getting an endless loop which I was unable to resolve when trying to get retrieve the attribute value inside that method.
Also note that you can alternatively use vars(). In the above example, you could exchange getattr(self,varname) by return vars(self)[varname], but getattrmight be preferable according to the answer to What is the difference between vars and setattr?.