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:
- What is the difference between
self.c = self.a + self.b
andc = self.a + self.b
? - Should all new variables declared inside classes be declared with the
self
statement?
Thanks for any help!
self.c
is a variable attached to the object whereasc
is a local variable. – Diacetylmorphineself.__class__.c = 10
(not recommended).self.c
is an instance variable (except whenself
isn't an instance,self
isn't a keyword in python!). – Logbook