Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 237
Litwos Avatar asked Mar 02 '17 14:03

Litwos


People also ask

Can you declare variables in methods?

Method variables are declared inside a method (c), or as an argument in a method declaration (b). The scope of c is from its declaration to the end of the method.

How do you declare a variable inside a class?

Class variables − Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block. There would only be one copy of each class variable per class, regardless of how many objects are created from it.

How do you add variables and methods in class?

Declaration of Class:The class body is enclosed between curly braces { and }. The data or variables, defined within a class are called instance variables. The code is contained within methods. Collectively, the methods and variables defined within a class are called members of the class.

How do you declare a variable inside a class in Python?

In Python, Class variables are declared when a class is being constructed. They are not defined inside any methods of a class because of this only one copy of the static variable will be created and shared between all objects of the class.


1 Answers

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.

like image 137
Tiago Castro Avatar answered Oct 18 '22 08:10

Tiago Castro