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
2 answers

Infinite loop using __getattr__ and getattr

Okay, I'm having a bit of a problem and I'm not quite sure why its occurring the way that it is. What I'm trying to do is allow access to attributes on an object via snake_case or camelCase in python 2.7.X I thought that __getattr__ was the correct…
loganasherjones
  • 1,012
  • 2
  • 11
  • 19
2
votes
1 answer

On-demand creation of member methods using __getattr__()

Given a class MyClass(object), how can I programmatically define class member methods using some template and the MyClass.__getattr__ mechanism? I'm thinking of something along the lines of class MyClass(object): def __init__(self,…
andreas-h
  • 10,679
  • 18
  • 60
  • 78
2
votes
2 answers

python how to use getattr on a class

I have a simple use case, I have a class: class A: def meth1(self, name): ... def meth2(self, name, funcname): # funcname is a string 'meth1' # how do I invoke meth1 by using funcname string here self.funcname(name)? I tried using…
waka-waka-waka
  • 1,025
  • 3
  • 14
  • 30
2
votes
1 answer

Why does getattr not act the same as manually newing up object

Can someone please explain why I get different output when I run the Python script below? I don't understand why getattr(sys.modules['importme'], 'MyClass') does not print the custom __repr__() function defined in…
E-rich
  • 9,243
  • 11
  • 48
  • 79
2
votes
1 answer

Switchable dot access to Python dicts?

I haven't seen a toggleable version of dictionary dot-access yet. My first-pass attempt here doesn't work: class DottableDict (dict): def allowDotting (self, state=True): if state: self.__setattr__ = dict.__setitem__ …
Gary Fixler
  • 5,632
  • 2
  • 23
  • 39
2
votes
2 answers

How to Dynamically Access Fields from Foreign Key in Django Admin

So I have models like this: class Celebrity(models.Model): #30+ fields here ... class HoneyBadger(models.Model): name = models.CharField(max_length=10) celebrity_owner = models.ForeignKey(Celebrity) Now I want the admin interface for…
Greg
  • 45,306
  • 89
  • 231
  • 297
2
votes
3 answers

Python: Using code to write code - For a beginner

The issue I'm having right now is loading a bunch of sound files as their own objects in Pygame. You load a sound with this syntax: sound1 = pygame.mixer.Sound('file.wav') Say I have seven files, and I want them loaded and named sound1 - sound7.…
Aygtets
  • 21
  • 2
2
votes
1 answer

How to access call parameters and arguments with __getattr__

I have the following code, where most of the code seem to look awkward, confusing and/or circumstantial, but most of it is to demonstrate the parts of the much larger code where I have a problem with. Please read carefully # The following part is…
Alex
  • 41,580
  • 88
  • 260
  • 469
2
votes
1 answer

gettattr , "attributes must be string" error in python

I am trying to use getattr function in my code using generator li=[] m=[method for method in dir(li) if callable(getattr(li,method))] print getattr(li,(str(i) for i in m)) Error: TypeError: getattr(): attribute name must be string if I am using…
sum2000
  • 1,363
  • 5
  • 21
  • 36
1
vote
1 answer

Extracting the value of a key with BeautifulSoup

I want to extract the value of the "archivo" key of something like this: ...
Antonio
  • 61
  • 1
  • 7
1
vote
1 answer

Why isn't there __setattribute__ in python?

Python has these methods: __getattr__, __getattribute__, and __setattr__. I know the difference between __getattr__ and __getattribute__, this thread explains it well. But I couldn't find anywhere anybody mentioning why __setattribute__ doesn't…
acmpo6ou
  • 840
  • 1
  • 12
  • 21
1
vote
2 answers

Can not make property and __getattr__ working together

I am working on a python class that has declared properties, and in which I want to add extra attributes at object instanciation (passed in the init method). I want them to be read and written. Finally, I don't want the user to be able to declare…
Gribouille
  • 102
  • 6
1
vote
1 answer

Is there a way to use __getattr__ as Python classmethod

getattr works pretty well with instance of class: class Person: def __getattr__(self, name): print(name) p = Person() p.john Output: john but it does not work as classmethod: class Person: @classmethod def __getattr__(cls,…
Dmytro
  • 25
  • 4
1
vote
1 answer

How to pass a parameter to a function from a class that has already a running instance with getattr - Python

I have a selenium web scraping object called Bot(). In my GUI I want to call methods via an input box. I have tried: bot = bot_module.Bot() function_string = "somefunction(parameter)" func_name = function_string.split("(")[0] func_param =…
1
vote
2 answers

TypeError: getattr(): attribute name must be string

I need to organize the ouput as a button in a telegram bot. I create, for example, a dictionary and I need to infer the key and the object from it, to form it as string and place it in a button that will go through the for loop. But instead of the…