Ely Fialkoff
Ely Fialkoff

Reputation: 652

When to use self and when not to use self

Which class option is preferable and why?

Option 1

class Person():
    def __init__(self):
        pass
    def sayHello(self, name):
        print "{} says hello!".format(name)
    def driver(self):
        for name in names:        # names is generated in the driver function by some means of input
            self.sayHello(name)

Option 2

class Person():
    def __init__(self):
        self.name = None
    def sayHello(self):
        print "{} says hello!".format(self.name)
    def driver(self):
        for name in names:        # names is generated in the driver function by some means of input
            self.name = name
            self.sayHello()

You can assume that there are more variables than just name and that multiple functions are using these variables. The main point I am trying to make is that the variable value's are changing inside the for loop

Upvotes: 0

Views: 521

Answers (1)

Blusky
Blusky

Reputation: 3804

Even though your exemple is syntaxically correct, it doesn't help at all understand your question regarding how to use a instance attribute.

From want I'm guessing, there's two questions :

  • When to use a class method (def foo(self, bar)) ?
  • When to use a instance attribute (self.name) ?

Instance attribute should be used when you need to "share" a variable between functions or retrieve it from outside a function. That variable will be "attached" to the object (for exemple, the color of a car, the nickname of a user, ...)

If your function / method need to call this kind of variable, it must use self to get it, so you have to set it as the first argument when defining this function.

If you just need a temporary variable to loop over it and do some stuff, you don't need to use a class method, a simple function will do the trick.

Upvotes: 1

Related Questions