Declaring new variables inside class methods

Question:

I just read about class and method variables in Python, and I am wondering if there is a difference between these two examples:

class Example(object):
    def __init__(self, nr1, nr2):
        self.a = nr1
        self.b = nr2

    def Add(self):
        c = self.a + self.b
        return c

class Example2(object):
    def __init__(self, nr1, nr2):
        self.a = nr1
        self.b = nr2

    def Add(self):
        self.c = self.a + self.b
        return self.c

Basically if I do:

print Example(3,4).Add()
print Example2(3,4).Add()

I get the same result:

7
7

So my questions are:

  1. What is the difference between self.c = self.a + self.b and c = self.a + self.b?
  2. Should all new variables declared inside classes be declared with the self statement?

Thanks for any help!

Asked By: Litwos

||

Answers:

1.- you can use self.c in other methods c no, is local variable.

2.- yes, with self.c.

3.- no, if you only need it in the current method you use local.

4.- inside __init__ or at the beginning of the class, it’s ok.

Answered By: ZiTAL

The difference is that on the second example you store the result of the addition to an object variable c. In the first example, c is inside a method and thus can not be a class variable since it is instantiated when the Add method is called and not when the class is defined.

Variables inside a method should be written with self just if you want to store them. A local, unimportant variable can be written inside a method just like you did on example with c.

Answered By: Tiago Castro
class Example(object):
    def __init__(self, nr1, nr2):
        self.a = nr1
        self.b = nr2

    def Add(self):
        c = self.a + self.b
        return c

Suppose if we create a instance x=Example().

If we try to accces c using x.c . We would get following error

AttributeError: ‘Example’ object has no attribute ‘c’.

Answered By: Kandan Siva

Actually self.c is an instance variable (defined with in the method) while c is a local variable with a limited scope within the class (garbage collector). The difference is that self.c can be looked upon by other methods or class objects by calling the self.add() method first which can initialize the self.c instance variable, on the other hand c can never be accessed by any other method in anyway.

Answered By: Khan

Answer 1: The difference is that variable "c" is local to the method where it’s defined and thus cannot be accessed or used outside the function.

Answer 2: It is not compulsory to define all instance variable in the __init__() method, Because objects are dicts you can add, delete and modify from methods.

Note:
Instance variables are defined with self, which ties the variable to a specific object.

Answered By: Solomon Uche
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.