Using getattr function on self in python

getattr, python

Solution

Firstly, do use CapitalLetters for Classes and lowercase_letters for variables as it is easier to read for other Python programmers :)

Now, you don't need to use getattr() inside the class itself Just do :

self.attribute

However, an example will be:

class Foo(object):            # Class Foo inherits from 'object'
    def __init__(self, a, b): # This is the initialize function. Add all arguments here
        self.a = a  # Setting attributes
        self.b = b

    def func(self):
        print('Hello World!' + str(self.a) + str(self.b))

>>> new_object = Foo(a=1, b=2) # Creating a new 'Foo' object called 'new_object'
>>> getattr(new_object, 'a') # Getting the 'a' attribute from 'new_object'
1

However, an easier way would just be referencing the attribute directly

>>> new_object.a
1
>>> new_object.func()
Hello World!12

Or, by using getattr():

>>> getattr(new_object, 'func')()
Hello World!12

Although I explained the getattr() function, I don't seem to understand what you want to achieve, do post a sample output.

Problem

I am trying to write call multiple functions through a loop using the `getattr(...)`. Snippet below: ``` class cl1(module): I =1 Name= 'name'+str(I) Func= 'func'+str(I) Namecall = gettattr(self,name) Namecall = getattr(self,name)() ``` This is when get the following code: `self.name1 = self.func1()` The desire is to loop multiple of these but the code is not working. Can you please advise?

Original source