Litwos
Litwos

Reputation: 1348

Declaring new variables inside class methods

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!

Upvotes: 13

Views: 16866

Answers (5)

Solomon Uche
Solomon Uche

Reputation: 31

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.

Upvotes: 0

Khan
Khan

Reputation: 1496

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.

Upvotes: 2

Kandan Siva
Kandan Siva

Reputation: 479

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'.

Upvotes: 5

Tiago Castro
Tiago Castro

Reputation: 46

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.

Upvotes: 3

ZiTAL
ZiTAL

Reputation: 3581

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.

Upvotes: 0

Related Questions