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:
self.c = self.a + self.b
and c = self.a + self.b
?self
statement?Thanks for any help!
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With