好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

python中关于类与实例如何绑定属性与方法的代码实例

最近在学习python,纯粹是自己的兴趣爱好,然而并没有系统地看python编程书籍,觉得上面描述过于繁琐,在网站找了一些学习的网站,下面这篇文章主要给大家介绍了关于python中类和实例时如何绑定属性与方法的相关资料,需要的朋友可以参考下。

 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# 
输出

注意这种方式只对实例a起作用,如果需要类Studnet的所有实例均可调用,那么直接给类Student绑定方法即可。

总结

以上就是python中关于类与实例如何绑定属性与方法的代码实例的详细内容,更多请关注Gxl网其它相关文章!

查看更多关于python中关于类与实例如何绑定属性与方法的代码实例的详细内容...

  阅读:43次