class Student(object): name = 'Student'
class Student(object): name = 'Student' s = Student() # 创建实例s print(s.name) # 打印name属性,因为实例并没有name属性,所以会继续查找class的name属性 print(Student.name) # 打印类的name属性 Student Student
s.name = 'xiaoming' # 给实例绑定name属性 print(s.name) # 由于实例属性优先级比类属性高,因此,它会屏蔽掉类的name属性 print(Student.name) # 但是类属性并未消失,用Student.name仍然可以访问 xiaoming Student
del s.name # 如果删除实例的name属性 print(s.name) # 再次调用s.name,由于实例的name属性没有找到,类的name属性就显示出来了 Student
class Student(object):
def __init__(self, name):
self.name = name
s = Student('Bob')#方法一 通过类的self变量绑定属性
s.score = 90#方法二 直接赋值
Class Student(object): pass a=Student()#创建实例 def set_score(self,score): self.score=score Student.set_score=set_score#类绑定方法 a.set_score(99)#调用方法 a.score 99#输出
Class Student(object): pass a=Student()#创建实例 def set_score(self,score): self.score=score from types import MethodType Student.set_score = MethodType(set_score, Student) a.set_score(99)#调用方法 a.score 99#输出
b=Student() b.set_score(60) b.score a.score 60
Class Student(object): pass a=Student()#创建实例 def set_score(self,score): self.score=score from types import MethodType a.set_score = MethodType(set_score, a) a.set_score(99)#调用方法 a.score 99#输出
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有