5

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?

Will
  • 24,082
  • 14
  • 97
  • 108
user3548782
  • 81
  • 1
  • 1
  • 2
  • Python is case-sensitive. `Class` needs to be `class` (and you should read PEP 8 and fix the rest of your capitalization.) I'm assuming "not working" means the first line is a syntax error, because you haven't told us what it actually means. – Wooble Apr 18 '14 at 12:28
  • `self` only exists inside a bound method; you don't have any methods here, nor is it clear what you are trying to achieve. – Martijn Pieters Apr 18 '14 at 12:28
  • @MartijnPieters or more correctly, `self` only exists when you use the name `self` for the first argument of a bounded method, as the first argument will be assigned a reference to the current object. – l4mpi Apr 18 '14 at 13:06
  • @l4mpi: yes, but I didn't want to make it more confusing to the OP still. The [descriptor protocol](https://docs.python.org/2/howto/descriptor.html) and how it relates to methods is not something I'd throw at beginners. – Martijn Pieters Apr 18 '14 at 13:08

1 Answers1

6

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.

Prateek Alat
  • 216
  • 2
  • 8