Try the inspect module. getmembers and the various tests should be helpful.
EDIT:
For example,
class MyClass(object):
a = '12'
b = '34'
def myfunc(self):
return self.a
>>> import inspect
>>> inspect.getmembers(MyClass, lambda a:not(inspect.isroutine(a)))
[('__class__', type),
('__dict__',
<dictproxy {'__dict__': <attribute '__dict__' of 'MyClass' objects>,
'__doc__': None,
'__module__': '__main__',
'__weakref__': <attribute '__weakref__' of 'MyClass' objects>,
'a': '34',
'b': '12',
'myfunc': <function __main__.myfunc>}>),
('__doc__', None),
('__module__', '__main__'),
('__weakref__', <attribute '__weakref__' of 'MyClass' objects>),
('a', '34'),
('b', '12')]
Now, the special methods and attributes get on my nerves- those can be dealt with in a number of ways, the easiest of which is just to filter based on name.
>>> attributes = inspect.getmembers(MyClass, lambda a:not(inspect.isroutine(a)))
>>> [a for a in attributes if not(a[0].startswith('__') and a[0].endswith('__'))]
[('a', '34'), ('b', '12')]
...and the more complicated of which can include special attribute name checks or even metaclasses ;)
Answer from Matt Luongo on Stack OverflowTry the inspect module. getmembers and the various tests should be helpful.
EDIT:
For example,
class MyClass(object):
a = '12'
b = '34'
def myfunc(self):
return self.a
>>> import inspect
>>> inspect.getmembers(MyClass, lambda a:not(inspect.isroutine(a)))
[('__class__', type),
('__dict__',
<dictproxy {'__dict__': <attribute '__dict__' of 'MyClass' objects>,
'__doc__': None,
'__module__': '__main__',
'__weakref__': <attribute '__weakref__' of 'MyClass' objects>,
'a': '34',
'b': '12',
'myfunc': <function __main__.myfunc>}>),
('__doc__', None),
('__module__', '__main__'),
('__weakref__', <attribute '__weakref__' of 'MyClass' objects>),
('a', '34'),
('b', '12')]
Now, the special methods and attributes get on my nerves- those can be dealt with in a number of ways, the easiest of which is just to filter based on name.
>>> attributes = inspect.getmembers(MyClass, lambda a:not(inspect.isroutine(a)))
>>> [a for a in attributes if not(a[0].startswith('__') and a[0].endswith('__'))]
[('a', '34'), ('b', '12')]
...and the more complicated of which can include special attribute name checks or even metaclasses ;)
def props(cls):
return [i for i in cls.__dict__.keys() if i[:1] != '_']
properties = props(MyClass)
introspection - Get all object attributes in Python? - Stack Overflow
python - Is there a way to access the formal parameters if you implement __getattribute__ - Stack Overflow
How can you set class attributes from variable arguments (kwargs) in python - Stack Overflow
Any way to get ALL attributes of an object in python?
What is a Python namespace?
A Python namespace is a mapping from names to objects, with the property that there is zero relation between names in different namespaces. Namespaces are usually implemented as Python dictionaries, although this is abstracted away.
What happens if both instance attribute and class attribute are defined?
In that case, the instance namespace takes precedence over the class namespace. If there is an attribute with the same name in both, the instance namespace will be checked first and its value returned.
Python class method versus instance method: What’s the difference?
In Python, a class method is a method that is invoked with the class as the context. This is often called a static method in other programming languages. An instance method, on the other hand, is invoked with an instance as the context.
Videos
This link here can explain more about class attributes/methods/parameters.
However, I do understand how complicated these concepts are, so I will answer your question (although in the future, try to ask a more specific question!).
In example one:
init (the initializer) and print_time are both class attributes. When you initialize the clock variable and pass in the parameter '5:30', it accesses the init function and hits the self.time = time line of code. Since time is accessed using a dot notation, time is an INSTANCE attribute (specific to the individual object).
When you call self.print_time(), the time there is a local variable specific to the function call, therefore the instance attribute is not changed. That is why when you print self.time it is still 5:30.
In example two:
In this case, the init and print_time functions are both class attributes (similar to the example above). The initialization of the clock object is the same as above. However, when it calls print_time, time is a the parameter '10:30', and therefore when we just print time (notice we did not use any dot notation), it prints only the local variable of '10:30'.
In example three:
init and print_time are both class attributes, same as the above two examples. When you initialize the boston_clock object, it is similar to both example one and two. Then you assign the name paris_clock to the object boston_block (notice that paris_clock and boston_clock are just names pointing to the same object, like how I could have two names). Therefore when we execute the line of code paris_clock.time = '10:30', the INSTANCE attribute of this single object is changed to '10:30'. However, since boston_clock is pointing to the same object as paris_clock, boston_clock's time attribute is also '10:30'.
Attributes are the variables within a class or instance. In something like this the variable hello is an attribute of the class Hi.
class Hi:
hello = "Hello World!"
Methods are functions within the class, so for something like this, function greet is a method of the class Hi.
class Hi:
def greet(self):
pass
Parameters are input(s) that go into a method. So the string, "Hello World!" is a parameter of the method say in the class Hi.
class Hi:
def say(self, saying):
print(saying)
Hi().say("Hello World!")
There's a nice question on the Software Engineering StackExchange site about OOPL. Explaining OOP Concepts to a non technical person.
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']
__getattribute__ simply returns the attribute that was requested, in case of a method, the __call__ interface is then used to call it.
Instead of returning the method, return a wrapper around it, for instance:
def __getattribute__(self, attr):
def make_interceptor(callble):
def func(*args, **kwargs):
print args, kwargs
return callble(*args, **kwargs)
return func
att = self.__dict__[attr]
if callable(att):
return make_interceptor(att)
Method invocation in Python is two step process, first a function is looked up, then it is invoked. For a more involved discussion see my answer to this question.
So you would need to do something like this:
def __getattribute__(self, key):
if key == "something_interesting":
def func(*args, **kwargs):
# use arguments, and possibly the self variable from outer scope
return func
else:
return object.__getattribute__(self, key)
Also, overriding __getattribute__ is usually a bad idea. Because it is called on all attribute accesses it is really easy to end up in an infinite loop, and even if you do everything correctly it ends up being a pretty big performance hit. Are you sure that __getattr__ won't be enough for your purposes? Or maybe even a descriptor object that returns functions. Descriptors are usually a lot better at reuse.
You could update the __dict__ attribute (which represents the instance attributes in the form of a dictionary) with the keyword arguments:
class Bar(object):
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
then you can:
>>> bar = Bar(a=1, b=2)
>>> bar.a
1
and with something like:
allowed_keys = {'a', 'b', 'c'}
self.__dict__.update((k, v) for k, v in kwargs.items() if k in allowed_keys)
you could filter the keys beforehand (use iteritems instead of items if you’re still using Python 2.x).
You can use the setattr() method:
class Foo:
def setAllWithKwArgs(self, **kwargs):
for key, value in kwargs.items():
setattr(self, key, value)
There is an analogous getattr() method for retrieving attributes.
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?