您的位置:首页 > 编程语言 > Python开发

python 类和实例绑定属性和方法的总结

2017-05-31 22:06 459 查看
由于Python是动态语言,类以及根据类创建的实例可以任意绑定属性以及方法,下面分别介绍。

1.类绑定属性

类绑定属性可以直接在class中定义属性,这种属性是类属。

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的值,会有如下结果:

s.name = 'xiaoming' # 给实例绑定name属性
print(s.name) # 由于实例属性优先级比类属性高,因此,它会屏蔽掉类的name属性
print(Student.name) # 但是类属性并未消失,用Student.name仍然可以访问
xiaoming
Student


接下来删除s.name属性:

del s.name # 如果删除实例的name属性
print(s.name) # 再次调用s.name,由于实例的name属性没有找到,类的name属性就显示出来了
Student


由此可见相同名称的实例属性将覆盖类属性,删除实例属性后,实例将向上访问到类属性。

2.实例绑定属性

实例绑定属性的方法有两种,一是通过类的self变量,二是直接给实例赋值。

class Student(object):
def __init__(self, name):
self.name = name
s = Student('Bob')  #方法一 通过类的self变量绑定属性
s.score = 90        #方法二 直接赋值


3.类绑定方法

类绑定方法分两种,第一种形如类绑定属性,例程如下:

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


第二种是使用MethodType给类绑定方法:

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:

b=Student()
b.set_score(60)
b.score
a.score
60
60


会发现a的属性score值也变成60。这里个人的理解是这里的score并不是同上一种方法一样直接绑定在类,而是类似于像列表一样的共享引用的关系,

即实例a和b都引用这个score作为自己的属性,而当其被修改时,所有引用它的实例的对应属性都将一同发生变化。

4.实例绑定方法

第一种通过给类绑定方法,可以使实例调用,如上所示。

第二种是使用MethodType给单个实例绑定方法。

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


注意这种方式只对实例a起作用,如果需要类Studnet的所有实例均可调用,那么直接给类Student绑定方法即可。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: