猛禽的编程艺术 2020-04-18
class
的实例后,可以给该实例绑定任何属性和方法,这还少动态语言的灵活性。s.set_age = MethodType(set_age, s)
class
绑定才能对所有实例起效。Student.set_score = set_score
__slots__
变量来限制class实例能添加的属性。__slots__
需要注意的是定义的属性仅对当前类实例起作用,对继承的子类是不起作用的。除非在子类中也定义__slots__
,这样子类实例允许定义的属性就是自身的__slots__
加上父类的__slots__
>>> class Student(object): ... __slots__ = (‘name‘, ‘age‘) ... >>> s = Student() # 创建新的实例 >>> s.name = ‘Michael‘ # 绑定属性‘name‘ >>> s.age = 25 # 绑定属性‘age‘ >>> s.score = 99 # 绑定属性‘score‘ Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: ‘Student‘ object has no attribute ‘score‘ e ‘score‘
@property
为内置的装饰器,负责把一个方法变成属性进行调用。#常规操作 class Student(object): def get_score(self): return self._score def set_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 >>> s = Student() >>> s.set_score(60) # ok! >>> s.get_score() 60 >>> s.set_score(9999) Traceback (most recent call last): ... ValueError: score must between 0 ~ 100!
@property
就可以了,此时property
本身又创建了另一个装饰器@score.setter
,负责把setter方法变成属性。于是,我们就拥有了一个可控的属性操作:#使用@property class Student(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 >>> s = Student() >>> s.score = 60 # OK,实际转化为s.set_score(60) >>> s.score # OK,实际转化为s.get_score() 60 >>> s.score = 9999 Traceback (most recent call last): ... ValueError: score must between 0 ~ 100!
class Student(object): @property def birth(self): return self._birth @birth.setter def birth(self, value): self._birth = value @property def age(self): return 2015 - self._birth
class Screen(object): @property def width(self): return self._width @width.setter def width(self, width): self._width = width @property def height(self): return self._height @height.setter def height(self, height): self._height = height @property def resolution(self): return self._width * self._height s = Screen() s.width = 1024 s.height = 768 print(‘resolution =‘, s.resolution) if s.resolution == 786432: print(‘测试通过!‘) else: print(‘测试失败!‘)
__str__:
#没有使用__str__ >>> class Student(object): ... def __init__(self, name): ... self.name = name ... >>> print(Student(‘Michael‘)) <__main__.Student object at 0x109afb190> #使用__str__ >>> class Student(object): ... def __init__(self, name): ... self.name = name ... def __str__(self): ... return ‘Student object (name: %s)‘ % self.name ... >>> print(Student(‘Michael‘)) Student object (name: Michael)
>>> s = Student(‘Michael‘) >>> s <__main__.Student object at 0x109afb310>
__str__()
,而是__repr__()
,两者的区别是__str__()
返回用户看到的字符串,而__repr__()
返回程序开发者看到的字符串,也就是说,__repr__()
是为调试服务的。__repr__()
。但是通常两者的代码是一样的,所以偷懒写法:class Student(object): def __init__(self, name): self.name = name def __str__(self): return ‘Student object (name=%s)‘ % self.name __repr__ = __str__
__iter__:
StopIteration
错误时退出。__getitem__:
__getattr__:
score
属性外,Python还有另一个机制,那就是写一个__getattr__
方法,动态返回一个属性。class Student(object): def __init__(self): self.name = ‘Michael‘ def __getattr__(self, attr): if attr = ‘score‘: return 99
__call__:
__call__
方法,就可以直接对实例进行调用。请看示例:class Student(object): def __init__(self, name): self.name = name def __call__(self): print(‘My name is %s‘ % self.name) 调用方式如下: >>> s = Student(‘Michael‘) >>> s() # self参数不要传入 My name is Michael.
callable()
函数,就可以了。Enum
类,来完成。value属性则是自动赋给成员的int
常量,默认从1开始计数。from enum import Enum, unique Month = Enum(‘Month‘, (‘Jan‘, ‘Feb‘, ‘Mar‘, ‘Apr‘, ‘May‘, ‘Jun‘, ‘Jul‘, ‘Aug‘, ‘Sep‘, ‘Oct‘, ‘Nov‘, ‘Dec‘)) for name, member in Month.__members__.items(): print(name, ‘=>‘, member, ‘,‘, member.value) @unique class Weekday(Enum): Sun = 0 Mon = 1 Tue = 2 Wed = 3 Thu = 4 Fri = 5 Sat = 6 day1 = Weekday.Mon print(day1) print(Weekday.Tue) print(Weekday[‘Tue‘]) print(Weekday.Tue.value) out: Jan => Month.Jan , 1 Feb => Month.Feb , 2 Mar => Month.Mar , 3 Apr => Month.Apr , 4 May => Month.May , 5 Jun => Month.Jun , 6 Jul => Month.Jul , 7 Aug => Month.Aug , 8 Sep => Month.Sep , 9 Oct => Month.Oct , 10 Nov => Month.Nov , 11 Dec => Month.Dec , 12 Weekday.Mon Weekday.Tue Weekday.Tue 2
type()
函数可以查看一个类型或变量的类型,Hello是一个class,它的类型就是type()
,而h是一个实例,它的类型就是classHello
type()
函数type()
函数即可以返回一个对象的类型,又可以创建出新的类型,比如我们可以通过type()
函数创建出Hello
类,而无需通过class Hello(oject)...
的定义:>>> Hello = type(‘Hello‘, (object,), dict(hello=fn)) # 创建Hello class >>> h = Hello() >>> h.hello() Hello, world. >>> print(type(Hello)) <class ‘type‘> >>> print(type(h)) <class ‘__main__.Hello‘>