I have two questions regarding the code below.
- What is the difference between
self.a=self.test1()
anda=self.test1()
? One is class field and other one is object field? - Why cannot I define
result = self.a self.b
? How to correct it?
class Test():
def __init__(self):
self.a=self.test1()
a=self.test1()
self.b=Test.test2()
result = self.a self.b
def test1(self):
a=100
return a
@classmethod
def test2(cls):
b=200
return b
@staticmethod
def test3():
print("Testing3 is calling ")
c=500
return c
CodePudding user response:
self.a = self.test1()
creates an instance attribute named a
. The attribute will be accessible from the object anywhere you have a reference to the object.
a = self.test1()
defines a local variable named a
. It will go out of scope once __init__
returns.
result = self.a self.b
doesn't work because it is in a context where self
is not defined. self
is just the (conventional) name of the first parameter of an instance method. It's not defined in the namespace of the class
statement itself.
CodePudding user response:
self.a
is a property in this class. It will remain accessible throughout functions in the Test()
class. a = self.test1()
, however, goes away once __init__(self)
finishes, because a
is local to __init__(self)
.
For result = self.a self.b
, I assume you want a variable called result
calculated after self.a
and self.b
is defined? At that indentation level a statement like this is usually not allowed (I could be wrong), usually a declaration of a property of a class happens here.