__init__
对象创建后,内存中就有一个对象的实例了
由此可见,一个类可以有很多个对象,每个对象都有属于自己的变量、方法;
self
如果不懂的话,看看下面代码的输出就知道啦; id() 是用于获取对象的内存地址
class person():
def __init__(self, name):
self.name = name
print(f"init-{self.name} ", id(self))
def test(self):
print(f"test-{self.name} ", id(self))
p1 = person("p1")
print("p1-", id(p1))
print("p1 fun-", id(p1.test()))
print("")
p2 = person("p2")
print("p2-", id(p2))
print("p2 fun-", id(p2.test()))
print("调用方法对比:",id(p1.test()) == id(p2.test()))
init-p1 1921848172840
p1- 1921848172840
test-p1 1921848172840
p1 fun- 140719454498016
init-p2 1921848175136
p2- 1921848175136
test-p2 1921848175136
p2 fun- 140719454498016
test-p1 1921848172840
test-p2 1921848175136
调用方法对比: True
实例属性=实例变量
类属性=类变量
class Person():
name = "cool guy"
if __name__ == "__main__":
p = Person()
print(p.name) # 打印name属性,因为实例并没有name属性,所以会继续查找class的name属性
print(Person.name) # 打印类的name属性
p.name = "bad guy" # 给实例绑定name属性
p.age = 12 # 给实例绑定age属性
print(p.age) # 实例找到age直接打印
print(p.name) # 由于实例属性优先级比类属性高,因此,它会屏蔽掉类的name属性
print(Person.name) # 仍然打印类的name属性
cool guy
cool guy
12
bad guy
cool guy
类方法会在下一篇幅介绍哦!