类的使用:实例化、属性引用
实例化
g1 = Garen(‘草丛伦1’) # 实例化
g2 = Garen(‘草丛伦2’)
g3 = Garen(‘草丛伦3’)
类的属性:变量和函数
print(Garen.camp)
print(Garen.attack)
print(Garen.dict)
1 2 3 4 5 6 7 8 9 10
| 结果: {'__module__': '__main__', '**camp**': 'Demecia', 'n': 3, '__init__': <function Garen.__init__ at 0x000000000231BB70>, '**attack**': <function Garen.attack at 0x000000000231BBF8>, '__dict__': <attribute '__dict__' of 'Garen' objects>, '__weakref__': <attribute '__weakref__' of 'Garen' objects>, '__doc__': None} 通过print(Garen.__dict__)能输出Garen类的名称空间,是一个字典,当我们进行使用的时候,实际是查找的是字典的key,通过key找相应的值 对类的变量的修改就是对其字典进行的修改: ```python Garen.camp = '123' # 找到字典的key--camp,修改camp的值为123 Garen.x = '123' # 在字典中新增一组
|
对象
对象也有一个名称空间(这个名称空间中国只有变量),也是字典形式的,可以通过下面的方式进行新增:
1 2
| g1.__dict__["12"]='123' print(g1.__dict__)
|
结果:
{‘nickname’: ‘草丛伦1’, ‘aggressive’: 58, ‘life_value’: 455, ‘hobby’: [], ‘12’: ‘123’}
实例化的对象 对类的属性引用
对象首先是引用自身的属性,对象的名称空间中只有自己的属性
1 2 3
| print(g1.nickname) print(g1.aggressive) print(Garen.camp)
|
类的属性是共享的,多个实例化的对象指向的是同一个变量的地址,是一样的内容,所以说是共享的
1 2 3
| print(g1.camp,id(g1.camp)) print(g2.camp,id(g2.camp)) print(g3.camp,id(g3.camp))
|
结果是:
Demecia 43096248
Demecia 43096248
Demecia 43096248
对象修改的是在自身的下面添加的,之后查找的时候是从首先从自己的内训寻找的
1 2 3 4
| g1.camp = '1111' print(g1.camp) print(g2.camp) print(g3.camp)
|
结果:
1111 # 查看的是自己内部的名称空间中的变量
Demecia
Demecia
小练习:对实例化的计数
关键: 每次实例化都会运行init,所以在init中写
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| class Garen: camp = 'Demecia' n = 0 def __init__(self,nickname,aggressive=58,life_value=455): self.nickname = nickname self.aggressive = aggressive self.life_value = life_value Garen.n += 1 self.hobby = [] def attack(self,enemy): enemy.life_value -= self.aggressive g1 = Garen('草丛伦1') g2 = Garen('草丛伦2') g3 = Garen('草丛伦3') print(g1.n) print(Garen.n)
|
结果:
3
3
绑定方法和函数
1 2
| print(g1.attack) print(Garen.attack)
|
结果:
bound method Garen.attack of <__main__.garen object="" at="" 0x00000000024546a0="">>
function Garen.attack at 0x000000000244BBF8>
1 2
| print(g1.attack(g1)) print(Garen.attack(g1,g1))
|