Questions tagged [getattr]

getattr is a Python built-in function used to access a named attribute on an object.

The function's schematics are as follows:

getattr(object:object, name:str[, default:object]) -> value

where object is the object, name is the named attribute, and default, if supplied, is the default value to return if the attribute can not be found. If default is not supplied and the object can not be found, an AttributeError is thrown.

Below is a demonstration of the function's features:

>>> class Test:
...     def __init__(self):
...         self.attr = 1
...
>>> myTest = Test()
>>> getattr(myTest, 'attr')
1
>>> getattr(myTest, 'attr2', 'No attribute by that name')
'No attribute by that name'
>>> getattr(myTest, 'attr2')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: Test instance has no attribute 'attr2'
>>>
378 questions
-2
votes
1 answer

python getattr returns to handler when exactly is handler set to None?

I'm porting a python script to .NET to make it easier to mantain and this is the first time i'm actually doing anything in python so I am heavily checking stackoverflow for every line I don't understand and I can't seem to figure this out at all. I…
SSpoke
  • 5,656
  • 10
  • 72
  • 124
-4
votes
2 answers

python object style access for dictionaries ; cant figure it out

class ObjectDict(dict): """ allows object style access for dictionaries """ def __getattr__(self, name): if name in self: return self[name] else: raise AttributeError('No such attribute: %s' % name) …
Arjun Biju
  • 73
  • 9
-6
votes
1 answer

How do I use getattr and setattr properly in Python?

I created a class in Python called Student. I need to create five instances of the class, and then be able to return an attribute from an instance of the user's choice, as well as set an attribute to a new value. Here is my code: class Student: …
Jasonca1
  • 4,848
  • 6
  • 25
  • 42
1 2 3
25
26