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
0
votes
1 answer

how to retrieve feature in xml file that is embedded in a tag using beautiful soup

i am trying to parse through a series of XML files and use beautiful soup to get certain values that are embedded in tags using beautiful soup using these functions: case_feature_keys = ['year', 'offenceCategory',…
Yaz
  • 15
  • 2
0
votes
1 answer

python jedi, autocompletion for dynamic attribute

I'm trying to write a class. Objects of that class can take a label/value pair and store it in such a way that label can be accessed as an attribute, returning value: obj.label -> value The main goal here is to get autocompletion in jupyter…
LcdDrm
  • 1,009
  • 7
  • 14
0
votes
2 answers

Trying to Print Values of Attributes... Code Needs Improvement

class User(): def __init__(self, first, last, location, gender): self.first = first self.last = last self.location = location self.gender = gender self.loginattempt = 0 def mmplusattempt(self): …
0
votes
0 answers

Iterating through an instance's attributes and stroting its values in a list, and using .join(), weird output

this is an example code from a book: class Car(): def __init__(self, make, model, year): self.make = make self.model = model self.year = year def describe(self): long = str(self.year) + ' ' + self.make + ' '…
0
votes
2 answers

How accessing object attributes that are stored in a DataFrame to assess conditions?

Please, is there any way to assess conditions on object attributes through loc when objects are stored in a pandas DataFrame? Something like: import pandas as pd from dataclasses import dataclass @dataclass(order=True, frozen=True) class…
pierre_j
  • 895
  • 2
  • 11
  • 26
0
votes
2 answers

python more generic solution for using getattr

say I have a test file with the following content: def a(): print('this is a') def b(x): print(x) and also a main file: import test def try_cmd(cmd, params): try: getattr(functions, cmd)(params) except Exception as…
NUAcKSha
  • 11
  • 2
0
votes
1 answer

Why python's getattr(obj,'method') and obj.method give different results? How do brackets affect?

My program calculated only sha256 file hash and I decided to expand the number of possible algorithms. So I started to use getattr() instead direct call. And the hashes have changed. It took me a while to figure out where the problem was, and here's…
Sidov
  • 3
  • 3
0
votes
0 answers

use the variable name Python. getattr()?

I have a list: car =['VW', 'Toyota', 'Audi'] I want to use the string 'car' without defining a new variable (just humor me, please.) Can it be done? Thanks
0
votes
0 answers

Combine mock and getattr

I want to make a mock object that is suitable for our teams tests. Howerver, the default getattr behavior is not what I want. See examples below. import mock class A(mock.MagicMock): pass a = A() print(a.something) # got a MagicMock without…
0
votes
1 answer

Using setattr() and getattr() in Python descriptors

While trying to create descriptors a few different ways I noticed some strange behavior that I'm trying to understand. Below are the three different ways I have gone about creating descriptors: >>> class NumericValueOne(): ... def __init__(self,…
readytotaste
  • 199
  • 2
  • 4
  • 17
0
votes
0 answers

Python method retrieved with getattr() does not need `self` in call? Why Not?

The following code works: class Foo: def run_this(self): print("ran this") ff = Foo() method = getattr(ff, "run_this") method() -- run_this But I don't understand why. If getattr returns a function object should I need to pass self to…
Ray Salemi
  • 5,247
  • 4
  • 30
  • 63
0
votes
1 answer

Python Data Enrichment - Calling functions based on Name-String with getattr

This is a little tutorial that I find very useful. It is a compilation of many questions that you can find here for example. I have tried to apply it to a real-world scenario to make it easier to understand. Let's imagine for a second that we have…
Nootaku
  • 217
  • 3
  • 14
0
votes
0 answers

Python logging library is printing logs on file two times?

I am working on a Python project where I will have to print the logs and at the same time store the logs in a file. The problem that's occurring is that the logs are getting printed in the console in the preferred way where each line is being…
Ashish101
  • 135
  • 10
0
votes
1 answer

Is it possible to set button state with dynamic name call using getattr and dictionary keys (Python 2.7, Tkinter)?

I'm building a python Tkinter GUI program containing buttons which will be enabled/disabled depending on various situations. For this reason, I want to refer to buttons dynamically rather than using static names. I've built a global dictionary that…
Jack
  • 3
  • 1
0
votes
0 answers

Debugging problems with deepcopy of class implementing __getattr__

I have a class which has an instance variable of type enum.Flag. It implements __getattr__ so that i can return the boolean state of a flag given by name. The code works fine when running without debugging, producing the expected output. However,…