请看下面代码:
class LineInfo():
Num = 4
def init(self):
#self.Num = 1 #Num of ‘:’ + 1
self.len = 2 #len of str before ‘:’ or ‘\n’
self.LineNum = 3
def say(self1):
self1.Num = 0
LineInfoObj = LineInfo()
print(LineInfoObj.Num)
LineInfoObj.say()
print(LineInfoObj.Num)
输出为
4
0
稍作改动:
class LineInfo():
Num = 4
def init(self):
self.Num = 1 #Num of ‘:’ + 1
self.len = 2 #len of str before ‘:’ or ‘\n’
self.LineNum = 3
def say(self1):
self1.Num = 0
LineInfoObj = LineInfo()
print(LineInfoObj.Num)
LineInfoObj.say()
print(LineInfoObj.Num)
输出为
1
0
总结:
因为类方法的第一个传参(习惯写为self,也可以为其他名字)代表对象自己的引用,所以__init_方法中通过赋值语句self.Num = 1,将原有的类变量Num = 4改为了Num = 1。(init()方法在创建对象时自动调用。)
再次调用Say方法,将Num值改为0
类调用实例方法:
class CLanguage:
bb = 1
def init(self):
self.b = 2
def info(self, b, c):
self.b = self.bb + b
self.c = c
print(self,"正在学 Python")
print(self.b + c)
#通过类名直接调用实例方法
obj = CLanguage()
obj.info(2,3)
obj.bb = 10
obj.info(2,3)
obj2 = CLanguage()
obj2.bb = 20
obj.info(2,3)
obj2.info(2,3)
CLanguage.bb = 2
obj.info(2,3)
obj2.info(2,3)
print()
print()
class CLanguage:
bb = 1
def info(self, b, c):
self.b = self.bb + b
self.c = c
print(self,“正在学 Python”)
print(self.b + c)
#通过类名直接调用实例方法
obj = CLanguage()
obj.info(2,3)
obj.bb = 10
obj.info(2,3)
obj2 = CLanguage()
obj2.bb = 20
obj.info(2,3)
obj2.info(2,3)
CLanguage.bb = 2
obj.info(2,3)
obj2.info(2,3)
CLanguage.info(obj, 2, 3)
CLanguage.info(obj2, 2, 3)
CLanguage.info(“obj”, 2, 3)
<main.CLanguage object at 0x000001C3CA578DF0> 正在学 Python
6
<main.CLanguage object at 0x000001C3CA578DF0> 正在学 Python
15
<main.CLanguage object at 0x000001C3CA578DF0> 正在学 Python
15
<main.CLanguage object at 0x000001C3CA578D30> 正在学 Python
25
<main.CLanguage object at 0x000001C3CA578DF0> 正在学 Python
15
<main.CLanguage object at 0x000001C3CA578D30> 正在学 Python
25
<main.CLanguage object at 0x000001C3CA578D00> 正在学 Python
6
<main.CLanguage object at 0x000001C3CA578D00> 正在学 Python
15
<main.CLanguage object at 0x000001C3CA578D00> 正在学 Python
15
<main.CLanguage object at 0x000001C3CA578D90> 正在学 Python
25
<main.CLanguage object at 0x000001C3CA578D00> 正在学 Python
15
<main.CLanguage object at 0x000001C3CA578D90> 正在学 Python
25
<main.CLanguage object at 0x000001C3CA578D00> 正在学 Python
15
<main.CLanguage object at 0x000001C3CA578D90> 正在学 Python
25