第三模块-第一章笔记(类实例化篇)

定义类与实例化
#定义父类 用于单位转换
class ScaleConverter:
def __init__(self,unit_from,unit_to,factor): #第一个参数必须是self
self.unit_from=unit_from
self.unit_to=unit_to
self.factor=factor
def description(self): #函数必须传入self,self用于区分是哪个对象调用该方法
return 'Convert '+self.unit_from+' to '+self.unit_to
def convert(self,value):
return value*self.factor


c1=ScaleConverter('inches','mm',25) #实例化类
print(c1.description())
print(str(c1.convert(2))+c1.unit_to)


属性查找与绑定方法
参考 https://www.cnblogs.com/seirios1993/p/6624157.html 博客

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)#调用方法
print(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起作用,如果需要类Studet的所有实例均可调用,那么直接给类Student绑定方法即可。
原文地址:https://www.cnblogs.com/changha0/p/8284751.html