面向对象高级
from enum import Enum, unique
from types import MethodType
class Student(object):
def __init__(self):
self=self
#实例绑定一个方法
s=Student()
def set_age(self,age):# 定义一个函数作为实例方法
self.age=age
s.set_age=MethodType(set_age,s)# 定义一个函数作为实例方法
s.set_age(25) # 调用实例方法
print(s.age)
#给一个实例绑定的方法,对另一个实例是不起作用的
#为了给所有实例都绑定方法,可以给class绑定方法
def set_score(self,score):
self.score=score
Student.set_score=set_score
s2=Student()
s2.set_score(100)
print(s2.score)
#使用__slots__
#Python允许在定义class的时候,定义一个特殊的__slots__变量,来限制该class实例能添加的属性
#__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的
#在子类中也定义__slots__,这样,子类实例允许定义的属性就是自身的__slots__加上父类的__slots__
class Student1(object):
__slots__ = ('name', 'age') # 用tuple定义允许绑定的属性名称
# 使用@property
# python内置装饰器@property负责吧一个方法(getter)变成属性调用,@property本身又创建另一个装饰器@score.setter负责把方法(setter)变成属性
class Student2(object):
@property
def score(self):
return self._score
@score.setter
def score(self, value):
if not isinstance(value, int):
raise ValueError('score must be an integer!')
if value < 0 or value > 100:
raise ValueError('score must between 0 ~ 100!')
self._score = value
#多重继承
#class Dog(Animal,Runnable):
#pass
#定制类 __xxx__
#__str__() print()时起作用
#__repr__()
#枚举类
Month=Enum('cc',('Jan'))
print(Enum('cc',('Jan')))
print(Month.Jan)
#自定义枚举
#@unique装饰器
@unique
class Weekday(Enum):
Sun=0
Mon=1
Tue=2
Wed=3
Thu=4
Fri=5
Sat=6
Weekday.Sun
print(Weekday.Sun)
print(Weekday.Sun.value)
#元类
#动态语言,函数和类实在运行时动态创建的(而不是在编译时定义)
#type()可以查看一个类型或者变量的类型
print(type(Month))
#type()动态创建类,一次传入3个参数:
#1.class的名称;2.继承的父类集合,tuple的单元素写法;3.方法的绑定
def fn(self,name='world'):
print('Hello,%s.' % name)
Hello=type('Hello',(object,),dict(hello=fn))
h1=Hello()
print(type(h1))
h1.hello()
#metaclass元类:先定义metaclass,然后创建类
#metaclass是python面向对象里最难理解的,也是最难使用的魔术代码,故以下内容先不详述