Iteration on members and attributes on a Class - python

I understand how to create an unsophisticated class based on examples culled from the Web but I hit a wall when trying to access the members on it, to wit:
Let's say this is my class:
class Fruit(object):
def __init__(self, name, color, flavor):
self.name = name
self.color = color
self.flavor = flavor
def description(self):
print('I am a %s %s and my taste is %s and I am %s' % self.color, self.name, self.flavor))
To create and object I use:
lemon = Fruit('lemon', 'yellow', 'sour')
and to create a new attribute for lemon I use:
lemon.peel = 'easy'
I would like to define a method inside (or outside) of the class that will be called printall that will iterate though all the existing members of the class and print all of them with their attributes even if the attributes are variable (more than de ones initially defined). I think this is called "overloading"
but I am not sure of the proper terminology.

The term you are looking for is type introspection. Overloading is something entirely different, where you provide different implementations of a method.
You can access all instance attributes with the var() function; it returns a dictionary you can then iterate over to print your variables:
def printall(self):
for name, value in vars(self).items():
print('self.{} = {!r}'.format(name, value))

And if you're not sure then you can use the below loop to find details of all members
import gc
#garbage collector should do the trick
#all the other code
for obj in gc.get_objects():
if isinstance(obj, Fruit):
print "object name :",obj.name
printall(obj)

perhaps this is what you're looking for, though the printall method is not a part of the class, it is able to access the class when you pass an object to it and the following code should print the attribute name and value of the object lemon in Fruits class.
def printall(lemon):
for a in dir(lemon):
if not a.startswith('__') :
print a,":",getattr(lemon, a)
#rest of the code
lemon = Fruit('lemon', 'yellow', 'sour')
lemon.peel = 'easy'
printall(lemon)

Related

Use variable passed to a function to call a member from a class in python [duplicate]

I read an article about the getattr function, but I still can't understand what it's for.
The only thing I understand about getattr() is that getattr(li, "pop") is the same as calling li.pop.
When and how do I use this exactly? The book said something about using it to get a reference to a function whose name isn't known until runtime, but when and why would I use this?
Objects in Python can have attributes -- data attributes and functions to work with those (methods). Actually, every object has built-in attributes (try dir(None), dir(True), dir(...), dir(dir) in Python console).
For example you have an object person, that has several attributes: name, gender, etc.
You access these attributes (be it methods or data objects) usually writing: person.name, person.gender, person.the_method(), etc.
But what if you don't know the attribute's name at the time you write the program? For example you have attribute's name stored in a variable called attr_name.
if
attr_name = 'gender'
then, instead of writing
gender = person.gender
you can write
gender = getattr(person, attr_name)
Some practice:
Python 3.4.0 (default, Apr 11 2014, 13:05:11)
>>> class Person():
... name = 'Victor'
... def say(self, what):
... print(self.name, what)
...
>>> getattr(Person, 'name')
'Victor'
>>> attr_name = 'name'
>>> person = Person()
>>> getattr(person, attr_name)
'Victor'
>>> getattr(person, 'say')('Hello')
Victor Hello
getattr will raise AttributeError if attribute with the given name does not exist in the object:
>>> getattr(person, 'age')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Person' object has no attribute 'age'
But you can pass a default value as the third argument, which will be returned if such attribute does not exist:
>>> getattr(person, 'age', 0)
0
You can use getattr along with dir to iterate over all attribute names and get their values:
>>> dir(1000)
['__abs__', '__add__', ..., '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
>>> obj = 1000
>>> for attr_name in dir(obj):
... attr_value = getattr(obj, attr_name)
... print(attr_name, attr_value, callable(attr_value))
...
__abs__ <method-wrapper '__abs__' of int object at 0x7f4e927c2f90> True
...
bit_length <built-in method bit_length of int object at 0x7f4e927c2f90> True
...
>>> getattr(1000, 'bit_length')()
10
A practical use for this would be to find all methods whose names start with test and call them.
Similar to getattr there is setattr which allows you to set an attribute of an object having its name:
>>> setattr(person, 'name', 'Andrew')
>>> person.name # accessing instance attribute
'Andrew'
>>> Person.name # accessing class attribute
'Victor'
>>>
getattr(object, 'x') is completely equivalent to object.x.
There are only two cases where getattr can be useful.
you can't write object.x, because you don't know in advance which attribute you want (it comes from a string). Very useful for meta-programming.
you want to provide a default value. object.y will raise an AttributeError if there's no y. But getattr(object, 'y', 5) will return 5.
For me, getattr is easiest to explain this way:
It allows you to call methods based on the contents of a string instead of typing the method name.
For example, you cannot do this:
obj = MyObject()
for x in ['foo', 'bar']:
obj.x()
because x is not of the type builtin, but str. However, you CAN do this:
obj = MyObject()
for x in ['foo', 'bar']:
getattr(obj, x)()
It allows you to dynamically connect with objects based on your input. I've found it useful when dealing with custom objects and modules.
A pretty common use case for getattr is mapping data to functions.
For instance, in a web framework like Django or Pylons, getattr makes it straightforward to map a web request's URL to the function that's going to handle it. If you look under the hood of Pylons's routing, for instance, you'll see that (by default, at least) it chops up a request's URL, like:
http://www.example.com/customers/list
into "customers" and "list". Then it searches for a controller class named CustomerController. Assuming it finds the class, it creates an instance of the class and then uses getattr to get its list method. It then calls that method, passing it the request as an argument.
Once you grasp this idea, it becomes really easy to extend the functionality of a web application: just add new methods to the controller classes, and then create links in your pages that use the appropriate URLs for those methods. All of this is made possible by getattr.
Here's a quick and dirty example of how a class could fire different versions of a save method depending on which operating system it's being executed on using getattr().
import os
class Log(object):
def __init__(self):
self.os = os.name
def __getattr__(self, name):
""" look for a 'save' attribute, or just
return whatever attribute was specified """
if name == 'save':
try:
# try to dynamically return a save
# method appropriate for the user's system
return getattr(self, self.os)
except:
# bail and try to return
# a default save method
return getattr(self, '_save')
else:
return getattr(self, name)
# each of these methods could have save logic specific to
# the system on which the script is executed
def posix(self): print 'saving on a posix machine'
def nt(self): print 'saving on an nt machine'
def os2(self): print 'saving on an os2 machine'
def ce(self): print 'saving on a ce machine'
def java(self): print 'saving on a java machine'
def riscos(self): print 'saving on a riscos machine'
def _save(self): print 'saving on an unknown operating system'
def which_os(self): print os.name
Now let's use this class in an example:
logger = Log()
# Now you can do one of two things:
save_func = logger.save
# and execute it, or pass it along
# somewhere else as 1st class:
save_func()
# or you can just call it directly:
logger.save()
# other attributes will hit the else
# statement and still work as expected
logger.which_os()
Other than all the amazing answers here, there is a way to use getattr to save copious lines of code and keeping it snug. This thought came following the dreadful representation of code that sometimes might be a necessity.
Scenario
Suppose your directory structure is as follows:
- superheroes.py
- properties.py
And, you have functions for getting information about Thor, Iron Man, Doctor Strange in superheroes.py. You very smartly write down the properties of all of them in properties.py in a compact dict and then access them.
properties.py
thor = {
'about': 'Asgardian god of thunder',
'weapon': 'Mjolnir',
'powers': ['invulnerability', 'keen senses', 'vortex breath'], # and many more
}
iron_man = {
'about': 'A wealthy American business magnate, playboy, and ingenious scientist',
'weapon': 'Armor',
'powers': ['intellect', 'armor suit', 'interface with wireless connections', 'money'],
}
doctor_strange = {
'about': ' primary protector of Earth against magical and mystical threats',
'weapon': 'Magic',
'powers': ['magic', 'intellect', 'martial arts'],
}
Now, let's say you want to return capabilities of each of them on demand in superheroes.py. So, there are functions like
from .properties import thor, iron_man, doctor_strange
def get_thor_weapon():
return thor['weapon']
def get_iron_man_bio():
return iron_man['about']
def get_thor_powers():
return thor['powers']
...and more functions returning different values based on the keys and superhero.
With the help of getattr, you could do something like:
from . import properties
def get_superhero_weapon(hero):
superhero = getattr(properties, hero)
return superhero['weapon']
def get_superhero_powers(hero):
superhero = getattr(properties, hero)
return superhero['powers']
You considerably reduced the number of lines of code, functions and repetition!
Oh and of course, if you have bad names like properties_of_thor for variables , they can be made and accessed by simply doing
def get_superhero_weapon(hero):
superhero = 'properties_of_{}'.format(hero)
all_properties = getattr(properties, superhero)
return all_properties['weapon']
NOTE: For this particular problem, there can be smarter ways to deal with the situation, but the idea is to give an insight about using getattr in right places to write cleaner code.
# getattr
class hithere():
def french(self):
print 'bonjour'
def english(self):
print 'hello'
def german(self):
print 'hallo'
def czech(self):
print 'ahoj'
def noidea(self):
print 'unknown language'
def dispatch(language):
try:
getattr(hithere(),language)()
except:
getattr(hithere(),'noidea')()
# note, do better error handling than this
dispatch('french')
dispatch('english')
dispatch('german')
dispatch('czech')
dispatch('spanish')
I sometimes use getattr(..) to lazily initialise attributes of secondary importance just before they are used in the code.
Compare the following:
class Graph(object):
def __init__(self):
self.n_calls_to_plot = 0
#...
#A lot of code here
#...
def plot(self):
self.n_calls_to_plot += 1
To this:
class Graph(object):
def plot(self):
self.n_calls_to_plot = 1 + getattr(self, "n_calls_to_plot", 0)
The advantage of the second way is that n_calls_to_plot only appears around the place in the code where it is used. This is good for readability, because (1) you can immediately see what value it starts with when reading how it's used, (2) it doesn't introduce a distraction into the __init__(..) method, which ideally should be about the conceptual state of the class, rather than some utility counter that is only used by one of the function's methods for technical reasons, such as optimisation, and has nothing to do with the meaning of the object.
Quite frequently when I am creating an XML file from data stored in a class I would frequently receive errors if the attribute didn't exist or was of type None. In this case, my issue wasn't not knowing what the attribute name was, as stated in your question, but rather was data ever stored in that attribute.
class Pet:
def __init__(self):
self.hair = None
self.color = None
If I used hasattr to do this, it would return True even if the attribute value was of type None and this would cause my ElementTree set command to fail.
hasattr(temp, 'hair')
>>True
If the attribute value was of type None, getattr would also return it which would cause my ElementTree set command to fail.
c = getattr(temp, 'hair')
type(c)
>> NoneType
I use the following method to take care of these cases now:
def getRealAttr(class_obj, class_attr, default = ''):
temp = getattr(class_obj, class_attr, default)
if temp is None:
temp = default
elif type(temp) != str:
temp = str(temp)
return temp
This is when and how I use getattr.
Another use of getattr() in implementing a switch statement in Python. It uses both reflection to get the case type.
import sys
class SwitchStatement(object):
""" a class to implement switch statement and a way to show how to use gettattr in Pythion"""
def case_1(self):
return "value for case_1"
def case_2(self):
return "value for case_2"
def case_3(self):
return "value for case_3"
def case_4(self):
return "value for case_4"
def case_value(self, case_type=1):
"""This is the main dispatchmethod, that uses gettattr"""
case_method = 'case_' + str(case_type)
# fetch the relevant method name
# Get the method from 'self'. Default to a lambda.
method = getattr(self, case_method, lambda: "Invalid case type")
# Call the method as we return it
return method()
def main(_):
switch = SwitchStatement()
print swtich.case_value(_)
if __name__ == '__main__':
main(int(sys.argv[1]))
setattr()
We use setattr to add an attribute to our class instance. We pass the class instance, the attribute name, and the value.
getattr()
With getattr we retrive these values
For example
Employee = type("Employee", (object,), dict())
employee = Employee()
# Set salary to 1000
setattr(employee,"salary", 1000 )
# Get the Salary
value = getattr(employee, "salary")
print(value)
I think this example is self explanatory. It runs the method of first parameter, whose name is given in the second parameter.
class MyClass:
def __init__(self):
pass
def MyMethod(self):
print("Method ran")
# Create an object
object = MyClass()
# Get all the methods of a class
method_list = [func for func in dir(MyClass) if callable(getattr(MyClass, func))]
# You can use any of the methods in method_list
# "MyMethod" is the one we want to use right now
# This is the same as running "object.MyMethod()"
getattr(object,'MyMethod')()
It is also clarifying from https://www.programiz.com/python-programming/methods/built-in/getattr
class Person:
age = 23
name = "Adam"
person = Person()
print('The age is:', getattr(person, "age"))
print('The age is:', person.age)
The age is: 23
The age is: 23
class Person:
age = 23
name = "Adam"
person = Person()
# when default value is provided
print('The sex is:', getattr(person, 'sex', 'Male'))
# when no default value is provided
print('The sex is:', getattr(person, 'sex'))
The sex is: Male
AttributeError: 'Person' object has no attribute 'sex'
I have tried in Python2.7.17
Some of the fellow folks already answered. However I have tried to call
getattr(obj, 'set_value') and this didn't execute the set_value method, So i changed to getattr(obj, 'set_value')() --> This helps to invoke the same.
Example Code:
Example 1:
class GETATT_VERIFY():
name = "siva"
def __init__(self):
print "Ok"
def set_value(self):
self.value = "myself"
print "oooh"
obj = GETATT_VERIFY()
print getattr(GETATT_VERIFY, 'name')
getattr(obj, 'set_value')()
print obj.value

Is it possible to call a models field with a string ? Access a class member variable using string? [duplicate]

I read an article about the getattr function, but I still can't understand what it's for.
The only thing I understand about getattr() is that getattr(li, "pop") is the same as calling li.pop.
When and how do I use this exactly? The book said something about using it to get a reference to a function whose name isn't known until runtime, but when and why would I use this?
Objects in Python can have attributes -- data attributes and functions to work with those (methods). Actually, every object has built-in attributes (try dir(None), dir(True), dir(...), dir(dir) in Python console).
For example you have an object person, that has several attributes: name, gender, etc.
You access these attributes (be it methods or data objects) usually writing: person.name, person.gender, person.the_method(), etc.
But what if you don't know the attribute's name at the time you write the program? For example you have attribute's name stored in a variable called attr_name.
if
attr_name = 'gender'
then, instead of writing
gender = person.gender
you can write
gender = getattr(person, attr_name)
Some practice:
Python 3.4.0 (default, Apr 11 2014, 13:05:11)
>>> class Person():
... name = 'Victor'
... def say(self, what):
... print(self.name, what)
...
>>> getattr(Person, 'name')
'Victor'
>>> attr_name = 'name'
>>> person = Person()
>>> getattr(person, attr_name)
'Victor'
>>> getattr(person, 'say')('Hello')
Victor Hello
getattr will raise AttributeError if attribute with the given name does not exist in the object:
>>> getattr(person, 'age')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Person' object has no attribute 'age'
But you can pass a default value as the third argument, which will be returned if such attribute does not exist:
>>> getattr(person, 'age', 0)
0
You can use getattr along with dir to iterate over all attribute names and get their values:
>>> dir(1000)
['__abs__', '__add__', ..., '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
>>> obj = 1000
>>> for attr_name in dir(obj):
... attr_value = getattr(obj, attr_name)
... print(attr_name, attr_value, callable(attr_value))
...
__abs__ <method-wrapper '__abs__' of int object at 0x7f4e927c2f90> True
...
bit_length <built-in method bit_length of int object at 0x7f4e927c2f90> True
...
>>> getattr(1000, 'bit_length')()
10
A practical use for this would be to find all methods whose names start with test and call them.
Similar to getattr there is setattr which allows you to set an attribute of an object having its name:
>>> setattr(person, 'name', 'Andrew')
>>> person.name # accessing instance attribute
'Andrew'
>>> Person.name # accessing class attribute
'Victor'
>>>
getattr(object, 'x') is completely equivalent to object.x.
There are only two cases where getattr can be useful.
you can't write object.x, because you don't know in advance which attribute you want (it comes from a string). Very useful for meta-programming.
you want to provide a default value. object.y will raise an AttributeError if there's no y. But getattr(object, 'y', 5) will return 5.
For me, getattr is easiest to explain this way:
It allows you to call methods based on the contents of a string instead of typing the method name.
For example, you cannot do this:
obj = MyObject()
for x in ['foo', 'bar']:
obj.x()
because x is not of the type builtin, but str. However, you CAN do this:
obj = MyObject()
for x in ['foo', 'bar']:
getattr(obj, x)()
It allows you to dynamically connect with objects based on your input. I've found it useful when dealing with custom objects and modules.
A pretty common use case for getattr is mapping data to functions.
For instance, in a web framework like Django or Pylons, getattr makes it straightforward to map a web request's URL to the function that's going to handle it. If you look under the hood of Pylons's routing, for instance, you'll see that (by default, at least) it chops up a request's URL, like:
http://www.example.com/customers/list
into "customers" and "list". Then it searches for a controller class named CustomerController. Assuming it finds the class, it creates an instance of the class and then uses getattr to get its list method. It then calls that method, passing it the request as an argument.
Once you grasp this idea, it becomes really easy to extend the functionality of a web application: just add new methods to the controller classes, and then create links in your pages that use the appropriate URLs for those methods. All of this is made possible by getattr.
Here's a quick and dirty example of how a class could fire different versions of a save method depending on which operating system it's being executed on using getattr().
import os
class Log(object):
def __init__(self):
self.os = os.name
def __getattr__(self, name):
""" look for a 'save' attribute, or just
return whatever attribute was specified """
if name == 'save':
try:
# try to dynamically return a save
# method appropriate for the user's system
return getattr(self, self.os)
except:
# bail and try to return
# a default save method
return getattr(self, '_save')
else:
return getattr(self, name)
# each of these methods could have save logic specific to
# the system on which the script is executed
def posix(self): print 'saving on a posix machine'
def nt(self): print 'saving on an nt machine'
def os2(self): print 'saving on an os2 machine'
def ce(self): print 'saving on a ce machine'
def java(self): print 'saving on a java machine'
def riscos(self): print 'saving on a riscos machine'
def _save(self): print 'saving on an unknown operating system'
def which_os(self): print os.name
Now let's use this class in an example:
logger = Log()
# Now you can do one of two things:
save_func = logger.save
# and execute it, or pass it along
# somewhere else as 1st class:
save_func()
# or you can just call it directly:
logger.save()
# other attributes will hit the else
# statement and still work as expected
logger.which_os()
Other than all the amazing answers here, there is a way to use getattr to save copious lines of code and keeping it snug. This thought came following the dreadful representation of code that sometimes might be a necessity.
Scenario
Suppose your directory structure is as follows:
- superheroes.py
- properties.py
And, you have functions for getting information about Thor, Iron Man, Doctor Strange in superheroes.py. You very smartly write down the properties of all of them in properties.py in a compact dict and then access them.
properties.py
thor = {
'about': 'Asgardian god of thunder',
'weapon': 'Mjolnir',
'powers': ['invulnerability', 'keen senses', 'vortex breath'], # and many more
}
iron_man = {
'about': 'A wealthy American business magnate, playboy, and ingenious scientist',
'weapon': 'Armor',
'powers': ['intellect', 'armor suit', 'interface with wireless connections', 'money'],
}
doctor_strange = {
'about': ' primary protector of Earth against magical and mystical threats',
'weapon': 'Magic',
'powers': ['magic', 'intellect', 'martial arts'],
}
Now, let's say you want to return capabilities of each of them on demand in superheroes.py. So, there are functions like
from .properties import thor, iron_man, doctor_strange
def get_thor_weapon():
return thor['weapon']
def get_iron_man_bio():
return iron_man['about']
def get_thor_powers():
return thor['powers']
...and more functions returning different values based on the keys and superhero.
With the help of getattr, you could do something like:
from . import properties
def get_superhero_weapon(hero):
superhero = getattr(properties, hero)
return superhero['weapon']
def get_superhero_powers(hero):
superhero = getattr(properties, hero)
return superhero['powers']
You considerably reduced the number of lines of code, functions and repetition!
Oh and of course, if you have bad names like properties_of_thor for variables , they can be made and accessed by simply doing
def get_superhero_weapon(hero):
superhero = 'properties_of_{}'.format(hero)
all_properties = getattr(properties, superhero)
return all_properties['weapon']
NOTE: For this particular problem, there can be smarter ways to deal with the situation, but the idea is to give an insight about using getattr in right places to write cleaner code.
# getattr
class hithere():
def french(self):
print 'bonjour'
def english(self):
print 'hello'
def german(self):
print 'hallo'
def czech(self):
print 'ahoj'
def noidea(self):
print 'unknown language'
def dispatch(language):
try:
getattr(hithere(),language)()
except:
getattr(hithere(),'noidea')()
# note, do better error handling than this
dispatch('french')
dispatch('english')
dispatch('german')
dispatch('czech')
dispatch('spanish')
I sometimes use getattr(..) to lazily initialise attributes of secondary importance just before they are used in the code.
Compare the following:
class Graph(object):
def __init__(self):
self.n_calls_to_plot = 0
#...
#A lot of code here
#...
def plot(self):
self.n_calls_to_plot += 1
To this:
class Graph(object):
def plot(self):
self.n_calls_to_plot = 1 + getattr(self, "n_calls_to_plot", 0)
The advantage of the second way is that n_calls_to_plot only appears around the place in the code where it is used. This is good for readability, because (1) you can immediately see what value it starts with when reading how it's used, (2) it doesn't introduce a distraction into the __init__(..) method, which ideally should be about the conceptual state of the class, rather than some utility counter that is only used by one of the function's methods for technical reasons, such as optimisation, and has nothing to do with the meaning of the object.
Quite frequently when I am creating an XML file from data stored in a class I would frequently receive errors if the attribute didn't exist or was of type None. In this case, my issue wasn't not knowing what the attribute name was, as stated in your question, but rather was data ever stored in that attribute.
class Pet:
def __init__(self):
self.hair = None
self.color = None
If I used hasattr to do this, it would return True even if the attribute value was of type None and this would cause my ElementTree set command to fail.
hasattr(temp, 'hair')
>>True
If the attribute value was of type None, getattr would also return it which would cause my ElementTree set command to fail.
c = getattr(temp, 'hair')
type(c)
>> NoneType
I use the following method to take care of these cases now:
def getRealAttr(class_obj, class_attr, default = ''):
temp = getattr(class_obj, class_attr, default)
if temp is None:
temp = default
elif type(temp) != str:
temp = str(temp)
return temp
This is when and how I use getattr.
Another use of getattr() in implementing a switch statement in Python. It uses both reflection to get the case type.
import sys
class SwitchStatement(object):
""" a class to implement switch statement and a way to show how to use gettattr in Pythion"""
def case_1(self):
return "value for case_1"
def case_2(self):
return "value for case_2"
def case_3(self):
return "value for case_3"
def case_4(self):
return "value for case_4"
def case_value(self, case_type=1):
"""This is the main dispatchmethod, that uses gettattr"""
case_method = 'case_' + str(case_type)
# fetch the relevant method name
# Get the method from 'self'. Default to a lambda.
method = getattr(self, case_method, lambda: "Invalid case type")
# Call the method as we return it
return method()
def main(_):
switch = SwitchStatement()
print swtich.case_value(_)
if __name__ == '__main__':
main(int(sys.argv[1]))
setattr()
We use setattr to add an attribute to our class instance. We pass the class instance, the attribute name, and the value.
getattr()
With getattr we retrive these values
For example
Employee = type("Employee", (object,), dict())
employee = Employee()
# Set salary to 1000
setattr(employee,"salary", 1000 )
# Get the Salary
value = getattr(employee, "salary")
print(value)
I think this example is self explanatory. It runs the method of first parameter, whose name is given in the second parameter.
class MyClass:
def __init__(self):
pass
def MyMethod(self):
print("Method ran")
# Create an object
object = MyClass()
# Get all the methods of a class
method_list = [func for func in dir(MyClass) if callable(getattr(MyClass, func))]
# You can use any of the methods in method_list
# "MyMethod" is the one we want to use right now
# This is the same as running "object.MyMethod()"
getattr(object,'MyMethod')()
It is also clarifying from https://www.programiz.com/python-programming/methods/built-in/getattr
class Person:
age = 23
name = "Adam"
person = Person()
print('The age is:', getattr(person, "age"))
print('The age is:', person.age)
The age is: 23
The age is: 23
class Person:
age = 23
name = "Adam"
person = Person()
# when default value is provided
print('The sex is:', getattr(person, 'sex', 'Male'))
# when no default value is provided
print('The sex is:', getattr(person, 'sex'))
The sex is: Male
AttributeError: 'Person' object has no attribute 'sex'
I have tried in Python2.7.17
Some of the fellow folks already answered. However I have tried to call
getattr(obj, 'set_value') and this didn't execute the set_value method, So i changed to getattr(obj, 'set_value')() --> This helps to invoke the same.
Example Code:
Example 1:
class GETATT_VERIFY():
name = "siva"
def __init__(self):
print "Ok"
def set_value(self):
self.value = "myself"
print "oooh"
obj = GETATT_VERIFY()
print getattr(GETATT_VERIFY, 'name')
getattr(obj, 'set_value')()
print obj.value

Return attribute values from object for list of attributes [duplicate]

I read an article about the getattr function, but I still can't understand what it's for.
The only thing I understand about getattr() is that getattr(li, "pop") is the same as calling li.pop.
When and how do I use this exactly? The book said something about using it to get a reference to a function whose name isn't known until runtime, but when and why would I use this?
Objects in Python can have attributes -- data attributes and functions to work with those (methods). Actually, every object has built-in attributes (try dir(None), dir(True), dir(...), dir(dir) in Python console).
For example you have an object person, that has several attributes: name, gender, etc.
You access these attributes (be it methods or data objects) usually writing: person.name, person.gender, person.the_method(), etc.
But what if you don't know the attribute's name at the time you write the program? For example you have attribute's name stored in a variable called attr_name.
if
attr_name = 'gender'
then, instead of writing
gender = person.gender
you can write
gender = getattr(person, attr_name)
Some practice:
Python 3.4.0 (default, Apr 11 2014, 13:05:11)
>>> class Person():
... name = 'Victor'
... def say(self, what):
... print(self.name, what)
...
>>> getattr(Person, 'name')
'Victor'
>>> attr_name = 'name'
>>> person = Person()
>>> getattr(person, attr_name)
'Victor'
>>> getattr(person, 'say')('Hello')
Victor Hello
getattr will raise AttributeError if attribute with the given name does not exist in the object:
>>> getattr(person, 'age')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Person' object has no attribute 'age'
But you can pass a default value as the third argument, which will be returned if such attribute does not exist:
>>> getattr(person, 'age', 0)
0
You can use getattr along with dir to iterate over all attribute names and get their values:
>>> dir(1000)
['__abs__', '__add__', ..., '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
>>> obj = 1000
>>> for attr_name in dir(obj):
... attr_value = getattr(obj, attr_name)
... print(attr_name, attr_value, callable(attr_value))
...
__abs__ <method-wrapper '__abs__' of int object at 0x7f4e927c2f90> True
...
bit_length <built-in method bit_length of int object at 0x7f4e927c2f90> True
...
>>> getattr(1000, 'bit_length')()
10
A practical use for this would be to find all methods whose names start with test and call them.
Similar to getattr there is setattr which allows you to set an attribute of an object having its name:
>>> setattr(person, 'name', 'Andrew')
>>> person.name # accessing instance attribute
'Andrew'
>>> Person.name # accessing class attribute
'Victor'
>>>
getattr(object, 'x') is completely equivalent to object.x.
There are only two cases where getattr can be useful.
you can't write object.x, because you don't know in advance which attribute you want (it comes from a string). Very useful for meta-programming.
you want to provide a default value. object.y will raise an AttributeError if there's no y. But getattr(object, 'y', 5) will return 5.
For me, getattr is easiest to explain this way:
It allows you to call methods based on the contents of a string instead of typing the method name.
For example, you cannot do this:
obj = MyObject()
for x in ['foo', 'bar']:
obj.x()
because x is not of the type builtin, but str. However, you CAN do this:
obj = MyObject()
for x in ['foo', 'bar']:
getattr(obj, x)()
It allows you to dynamically connect with objects based on your input. I've found it useful when dealing with custom objects and modules.
A pretty common use case for getattr is mapping data to functions.
For instance, in a web framework like Django or Pylons, getattr makes it straightforward to map a web request's URL to the function that's going to handle it. If you look under the hood of Pylons's routing, for instance, you'll see that (by default, at least) it chops up a request's URL, like:
http://www.example.com/customers/list
into "customers" and "list". Then it searches for a controller class named CustomerController. Assuming it finds the class, it creates an instance of the class and then uses getattr to get its list method. It then calls that method, passing it the request as an argument.
Once you grasp this idea, it becomes really easy to extend the functionality of a web application: just add new methods to the controller classes, and then create links in your pages that use the appropriate URLs for those methods. All of this is made possible by getattr.
Here's a quick and dirty example of how a class could fire different versions of a save method depending on which operating system it's being executed on using getattr().
import os
class Log(object):
def __init__(self):
self.os = os.name
def __getattr__(self, name):
""" look for a 'save' attribute, or just
return whatever attribute was specified """
if name == 'save':
try:
# try to dynamically return a save
# method appropriate for the user's system
return getattr(self, self.os)
except:
# bail and try to return
# a default save method
return getattr(self, '_save')
else:
return getattr(self, name)
# each of these methods could have save logic specific to
# the system on which the script is executed
def posix(self): print 'saving on a posix machine'
def nt(self): print 'saving on an nt machine'
def os2(self): print 'saving on an os2 machine'
def ce(self): print 'saving on a ce machine'
def java(self): print 'saving on a java machine'
def riscos(self): print 'saving on a riscos machine'
def _save(self): print 'saving on an unknown operating system'
def which_os(self): print os.name
Now let's use this class in an example:
logger = Log()
# Now you can do one of two things:
save_func = logger.save
# and execute it, or pass it along
# somewhere else as 1st class:
save_func()
# or you can just call it directly:
logger.save()
# other attributes will hit the else
# statement and still work as expected
logger.which_os()
Other than all the amazing answers here, there is a way to use getattr to save copious lines of code and keeping it snug. This thought came following the dreadful representation of code that sometimes might be a necessity.
Scenario
Suppose your directory structure is as follows:
- superheroes.py
- properties.py
And, you have functions for getting information about Thor, Iron Man, Doctor Strange in superheroes.py. You very smartly write down the properties of all of them in properties.py in a compact dict and then access them.
properties.py
thor = {
'about': 'Asgardian god of thunder',
'weapon': 'Mjolnir',
'powers': ['invulnerability', 'keen senses', 'vortex breath'], # and many more
}
iron_man = {
'about': 'A wealthy American business magnate, playboy, and ingenious scientist',
'weapon': 'Armor',
'powers': ['intellect', 'armor suit', 'interface with wireless connections', 'money'],
}
doctor_strange = {
'about': ' primary protector of Earth against magical and mystical threats',
'weapon': 'Magic',
'powers': ['magic', 'intellect', 'martial arts'],
}
Now, let's say you want to return capabilities of each of them on demand in superheroes.py. So, there are functions like
from .properties import thor, iron_man, doctor_strange
def get_thor_weapon():
return thor['weapon']
def get_iron_man_bio():
return iron_man['about']
def get_thor_powers():
return thor['powers']
...and more functions returning different values based on the keys and superhero.
With the help of getattr, you could do something like:
from . import properties
def get_superhero_weapon(hero):
superhero = getattr(properties, hero)
return superhero['weapon']
def get_superhero_powers(hero):
superhero = getattr(properties, hero)
return superhero['powers']
You considerably reduced the number of lines of code, functions and repetition!
Oh and of course, if you have bad names like properties_of_thor for variables , they can be made and accessed by simply doing
def get_superhero_weapon(hero):
superhero = 'properties_of_{}'.format(hero)
all_properties = getattr(properties, superhero)
return all_properties['weapon']
NOTE: For this particular problem, there can be smarter ways to deal with the situation, but the idea is to give an insight about using getattr in right places to write cleaner code.
# getattr
class hithere():
def french(self):
print 'bonjour'
def english(self):
print 'hello'
def german(self):
print 'hallo'
def czech(self):
print 'ahoj'
def noidea(self):
print 'unknown language'
def dispatch(language):
try:
getattr(hithere(),language)()
except:
getattr(hithere(),'noidea')()
# note, do better error handling than this
dispatch('french')
dispatch('english')
dispatch('german')
dispatch('czech')
dispatch('spanish')
I sometimes use getattr(..) to lazily initialise attributes of secondary importance just before they are used in the code.
Compare the following:
class Graph(object):
def __init__(self):
self.n_calls_to_plot = 0
#...
#A lot of code here
#...
def plot(self):
self.n_calls_to_plot += 1
To this:
class Graph(object):
def plot(self):
self.n_calls_to_plot = 1 + getattr(self, "n_calls_to_plot", 0)
The advantage of the second way is that n_calls_to_plot only appears around the place in the code where it is used. This is good for readability, because (1) you can immediately see what value it starts with when reading how it's used, (2) it doesn't introduce a distraction into the __init__(..) method, which ideally should be about the conceptual state of the class, rather than some utility counter that is only used by one of the function's methods for technical reasons, such as optimisation, and has nothing to do with the meaning of the object.
Quite frequently when I am creating an XML file from data stored in a class I would frequently receive errors if the attribute didn't exist or was of type None. In this case, my issue wasn't not knowing what the attribute name was, as stated in your question, but rather was data ever stored in that attribute.
class Pet:
def __init__(self):
self.hair = None
self.color = None
If I used hasattr to do this, it would return True even if the attribute value was of type None and this would cause my ElementTree set command to fail.
hasattr(temp, 'hair')
>>True
If the attribute value was of type None, getattr would also return it which would cause my ElementTree set command to fail.
c = getattr(temp, 'hair')
type(c)
>> NoneType
I use the following method to take care of these cases now:
def getRealAttr(class_obj, class_attr, default = ''):
temp = getattr(class_obj, class_attr, default)
if temp is None:
temp = default
elif type(temp) != str:
temp = str(temp)
return temp
This is when and how I use getattr.
Another use of getattr() in implementing a switch statement in Python. It uses both reflection to get the case type.
import sys
class SwitchStatement(object):
""" a class to implement switch statement and a way to show how to use gettattr in Pythion"""
def case_1(self):
return "value for case_1"
def case_2(self):
return "value for case_2"
def case_3(self):
return "value for case_3"
def case_4(self):
return "value for case_4"
def case_value(self, case_type=1):
"""This is the main dispatchmethod, that uses gettattr"""
case_method = 'case_' + str(case_type)
# fetch the relevant method name
# Get the method from 'self'. Default to a lambda.
method = getattr(self, case_method, lambda: "Invalid case type")
# Call the method as we return it
return method()
def main(_):
switch = SwitchStatement()
print swtich.case_value(_)
if __name__ == '__main__':
main(int(sys.argv[1]))
setattr()
We use setattr to add an attribute to our class instance. We pass the class instance, the attribute name, and the value.
getattr()
With getattr we retrive these values
For example
Employee = type("Employee", (object,), dict())
employee = Employee()
# Set salary to 1000
setattr(employee,"salary", 1000 )
# Get the Salary
value = getattr(employee, "salary")
print(value)
I think this example is self explanatory. It runs the method of first parameter, whose name is given in the second parameter.
class MyClass:
def __init__(self):
pass
def MyMethod(self):
print("Method ran")
# Create an object
object = MyClass()
# Get all the methods of a class
method_list = [func for func in dir(MyClass) if callable(getattr(MyClass, func))]
# You can use any of the methods in method_list
# "MyMethod" is the one we want to use right now
# This is the same as running "object.MyMethod()"
getattr(object,'MyMethod')()
It is also clarifying from https://www.programiz.com/python-programming/methods/built-in/getattr
class Person:
age = 23
name = "Adam"
person = Person()
print('The age is:', getattr(person, "age"))
print('The age is:', person.age)
The age is: 23
The age is: 23
class Person:
age = 23
name = "Adam"
person = Person()
# when default value is provided
print('The sex is:', getattr(person, 'sex', 'Male'))
# when no default value is provided
print('The sex is:', getattr(person, 'sex'))
The sex is: Male
AttributeError: 'Person' object has no attribute 'sex'
I have tried in Python2.7.17
Some of the fellow folks already answered. However I have tried to call
getattr(obj, 'set_value') and this didn't execute the set_value method, So i changed to getattr(obj, 'set_value')() --> This helps to invoke the same.
Example Code:
Example 1:
class GETATT_VERIFY():
name = "siva"
def __init__(self):
print "Ok"
def set_value(self):
self.value = "myself"
print "oooh"
obj = GETATT_VERIFY()
print getattr(GETATT_VERIFY, 'name')
getattr(obj, 'set_value')()
print obj.value

How to Instantiate One of Many Inheriting Classes Without if

Say for example I have some classes which all inherent from the same parent class and have the same parameters. A common example;
class Pet():
...
class Cat(Pet):
__init__(self,name,colour):
Pet.__init__(self,name,colour)
....
class Cactus(Pet):
__init__(self,name,colour):
Pet.__init__(self,name,colour)
....
And then say I want to instantite some type of pet later in the program based on user input. What I would think of doing at first is;
if(pet_type == 'Cat'):
animal = Cat(name,colour)
elif(pet_type == 'Cactus'):
animal = Cactus(name,colour)
etc...
But is there a better way that does not require an if? For example if the program was developed to include over 1000 animals which all descend from pet then it would not be feasilbe.
Create a dictionary of allowable classes:
classes = {
'Cat': Cat,
'Cactus': Cactus,
}
try:
cls = classes[pet_type]
except KeyError:
# handle invalid pet_type here
else:
animal = cls(name, colour)
Depending on your response to a KeyError, you may want to use a finally clause instead of an else clause, or simply use the get method of the dict, e.g.
animal = classes.get(pet_type, Pet)(name, colour)
What you look for is known as factory pattern. There is a great many ways of achieving this, ranging from explicit if-cascades as you show them to meta-class magic.
A rather straightforward way is a class-decorator:
PET_CLASSES = {}
def pet_class(cls):
PET_CLASSES[cls.__name__.lower()] = cls
def create_pet(name):
return PET_CLASSES[name.lower()]()
#pet_class
class Cat:
pass
#pet_class
class Dog:
pass
print(create_pet("dog"))
You can get the class by its string name with getattr()
my_class = getattr(module, "class_name")
and then
my_object = my_class(...)
The module object can be accessed by module = __import__("module_name")

python multiple nested classes

This is going to look like class inheritance but I think it is not and there must be an easy way of doing the following. Take a look at this simple code:
class Land:
def __init__(self):
print "a new Land"
self.farms = []
def addfarm(self):
self.farms.append(Farm())
class Farm:
def __init__(self):
print "a new farm"
self.animals = []
def addanimal(self,name):
self.animals.append(Animal(name))
class Animal:
def __init__(self, name):
print "hi, I am %s" % name
self.name = name
USA = Land()
USA.addfarm()
USA.farms[0].addanimal('George')
USA.farms[0].addanimal('Martin')
USA.addfarm()
USA.farms[1].addanimal('Polly')
USA.farms[1].addanimal('Ralph')
Is there an easy way of getting all animals without doing?:
for eachfarm in USA.farms:
for each in eachfarm.animals:
print each.name
I am asking this because if for instance the user wants to add a new George to farm 0 I would like to quickly be able to say that name is taken. I would also be able to quickly run a function that gives me all animals in the land or all farms. Should I be writing functions for all that or Python got its own?
I am also interested on knowing if my nested class structure is not correct and could end up causing issues.
For instance, lets say I have a function that given an animal tells me the perfect food mix for it. I would like to be able to run that function on all my animals and write back into their object. If they are nested I am afraid the function may get confused!
Thanks!
Using nested classes like this is perfectly fine and is not about inheritance at all. However you may want to choose slightly different data structures.
You say that in each farm you only want to be able to have one animal of each name. However, you use a list to store them. A list allows you to have as many animals of the same name inside as you want to, so you'd need to perform that check yourself when you add another one.
However, you could use a dict. A dict is an unordered data structure that links a key to a value. In your case you could use the name of the animal as the key and the Animal object for the value. Checking if a key exists can be done in constant time (as compared to linear time with a loop), since internally a dict is a hash table.
Example code might look like this:
class Land:
def __init__(self):
print "a new Land"
self.farms = []
def addfarm(self):
self.farms.append(Farm())
class Farm:
def __init__(self):
print "a new farm"
self.animals = {}
def addanimal(self,name):
if not name in self.animals:
self.animals[name] = Animal(name)
return True
return False
class Animal:
def __init__(self, name):
print "hi, I am %s" % name
self.name = name
USA = Land()
USA.addfarm()
USA.farms[0].addanimal('George')
USA.farms[0].addanimal('Martin')
USA.addfarm()
USA.farms[1].addanimal('Polly')
USA.farms[1].addanimal('Ralph')
This would prevent you from adding two animals of the same name to one farm, returning a boolean depending on whether the animal could be added to the farm or not.
To get all animals on all farms you will still need nested loops. But enabling iteration over the objects itself can be much nicer. If you do the following:
class Land(object):
def __init__(self):
print "a new Land"
self.farms = []
def addfarm(self):
self.farms.append(Farm())
def __iter__(self):
for farm in self.farms:
yield farm
class Farm(object):
def __init__(self):
print "a new farm"
self.animals = {}
def addanimal(self,name):
if not name in self.animals:
self.animals[name] = Animal(name)
return True
return False
def __iter__(self):
for name, animal in self.animals.iteritems():
yield animal
class Animal(object):
def __init__(self, name):
print "hi, I am %s" % name
self.name = name
You could then:
for farm in USA:
for animal in farm:
pass #do something here
According to your comment, you also want to be able to do land.getAllAnimals() and farm.getAllAnimals(). The latter is easily accomplished because farm works as an iterator over all animals. If you want a list you can simply call list(farm).
For land.getAllAnimals() there are two nice options. Both are to be added to the previous declaration.
Option 1
class Land(object):
def getAllAnimals(self):
for farm in self:
for animal in farm:
yield animal
Option 2
from itertools import chain
class Land(object):
def getAllAnimals(self):
return chain(*self)
Both will return iterators over all animals. To cast these into a list, simply call list on them. The former is easier to understand, but the latter is more concise and, in my opinion, nicer.
There is nothing wrong with nesting your loops, and it's just the way to do it. You might want to look into a more declarative approach, or you might want to store your data differently, but that's all just implementation detail and primarily a matter of taste.

Categories

Resources