Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1098079
  • 博文数量: 254
  • 博客积分: 1242
  • 博客等级: 少尉
  • 技术积分: 1581
  • 用 户 组: 普通用户
  • 注册时间: 2012-05-03 21:49
文章分类

全部博文(254)

文章存档

2017年(16)

2016年(4)

2013年(94)

2012年(140)

分类: Python/Ruby

2017-10-22 16:41:14

由于Python是动态语言,类以及根据类创建的实例可以任意绑定属性以及方法,下面分别介绍。

1.类绑定属性

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

1 class Student(object): 2 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 99#输出
复制代码

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

阅读(924) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~