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
3
votes
3 answers

Python getattr() with another attribute as the default

I have two classes. One class has an attribute x but not y, and the other class has an attribute y but not x. I have a function that accepts either class as an argument. Is there a one-line way to assign a new variable to the x attribute if it…
user2034412
  • 4,102
  • 2
  • 23
  • 22
3
votes
0 answers

Glusterfs Gett Attribute IOPS Caching

I'm building a GlusterFS share for a heavy Get Attribute workload. This cluster is configured in "Replicated fashion" and needs to host several TB of data. In this scenario the largest part of request from clients is of type "Get Attribute" ( eg.…
3
votes
1 answer

How do you slice a pandas dataframe as an argument in a function?

What I am looking to do is to put the rules of slicing a pandas dataframe in a function. For example: row1 = {'a':5,'b':6,'c':7,'d':'A'} row2 = {'a':8,'b':9,'c':10,'d':'B'} row3 = {'a':11,'b':12,'c':13,'d':'C'} df = pd.DataFrame([row1,row2,row3]) I…
fpes
  • 964
  • 11
  • 22
3
votes
2 answers

How to invoke a method with the methods name as a string

I am using Biopython's Restriction class to perform in silico restriction digestions. As I understand it, in order to digest a certain sequence with a certain enzyme, the .catalyze() method must be implemented. digestTuple =…
Malonge
  • 1,980
  • 5
  • 23
  • 33
3
votes
2 answers

Why does the "name" parameter to __setattr__ include the class, but __getattr__ doesn't?

The following code: class MyClass(): def test(self): self.__x = 0 def __setattr__(self, name, value): print name def __getattr__(self, name): print name raise AttributeError(name) x =…
Draemon
  • 33,955
  • 16
  • 77
  • 104
3
votes
2 answers

maximum recursion depth while using __setattr__ in python new style object?

I have the following code which comprises of a person class and a Manager class that delegates to a person class. I am using new style object(derived from object) and running python 2.7. I geth maximum recursion depth which I am unable to…
brain storm
  • 30,124
  • 69
  • 225
  • 393
3
votes
2 answers

netCDF Python: How to get the data type of an attribute of a variable?

I am using netCDF4 Python package, I know that getattr() can get the value of the attribute of a variable of a dataset, e.g. root = Dataset(file_name,'r') for var in root.variables.values(): print 'attrs of this variable:',var.ncattrs() for…
oldnavy
  • 177
  • 1
  • 3
  • 9
3
votes
1 answer

django: getattr function (get field name)

I can't make the function getattr work. Here is my code: print ConfigConsModel()._meta.get_all_field_names() #['codesectrepmodel', 'configCons', 'id'] modelInstance=ConfigConsModel() newAttrName1=getattr(modelInstance, "configCons") print…
rom
  • 3,592
  • 7
  • 41
  • 71
3
votes
1 answer

Get attributes for class and instance in python

In python work next code: class MyClass(object): field = 1 >>> MyClass.field 1 >>> MyClass().field 1 When I want return value for custom fields I use next code: class MyClass(object): def __getattr__(self, name): if…
tbicr
  • 24,790
  • 12
  • 81
  • 106
3
votes
2 answers

How to handle & return both properties AND functions missing in a Python class using the __getattr__ function?

It is fairly easy to use the __getattr__ special method on Python classes to handle either missing properties or functions, but seemingly not both at the same time. Consider this example which handles any property requested which is not defined…
sansjoe
  • 262
  • 3
  • 14
3
votes
1 answer

Learn Python The Hard Way: Exercise 43 Function Creation

while True: print "\n--------" room = getattr(self, next) next = room() My question stems from the block of code above, found in Learn Python The Hard Way - Exercise 43. I understand that the third line stores the getattr() function…
Arc'
  • 65
  • 1
  • 2
  • 4
3
votes
2 answers

Why is __getattr__ not invoked for missing "magically" invoked methods?

I am trying to implement a class in which an attempt to access any attributes that do not exist in the current class or any of its ancestors will attempt to access those attributes from a member. Below is a trivial version of what I am trying to…
Tyler Crompton
  • 12,284
  • 14
  • 65
  • 94
2
votes
1 answer

Python intercept method call

Let me start by saying what I would like to do. I want to create a lazy wrapper for a variable, as in I record all the method calls and operator calls and evaluate them later when I specify the variable to call it on. As such, I want to be able to…
norcalli
  • 1,215
  • 2
  • 11
  • 22
2
votes
3 answers

__setattr__ only for names not found in the object's attributes`?

I want to use __setattr__ only when the attribute was not found in the object's attributes, like __getattr__. Do I really have to use try-except? def __setattr__(self, name, value): try: setattr(super(Clazz, self), name, value) …
Niklas R
  • 16,299
  • 28
  • 108
  • 203
2
votes
4 answers

Django access related property dynamically?

I am using getattr to access properties of a model dynamically like so (Assuming the Student model has a property called name): students = Student.objects.all() property = 'name' for student in students: print getattr(student, property) This…
Dan
  • 6,265
  • 8
  • 40
  • 56