Python面向对象高级编程(__slots__、多继承、定制类)-6
2021-02-13 06:21
标签:动态创建 tween __call__ mic 多重继承 ext oct property %s Python面向对象高级编程(__slots__、多继承、定制类)-6 标签:动态创建 tween __call__ mic 多重继承 ext oct property %s 原文地址:https://www.cnblogs.com/tsruixi/p/12728510.html一、使用__slots__
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 "
二、使用@property
@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 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 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(‘测试失败!‘)
三、多继承
四、定制类
1.
__str__:
#没有使用__str__
>>> class Student(object):
... def __init__(self, name):
... self.name = name
...
>>> print(Student(‘Michael‘))
<__main__.student object at>
#使用__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>
__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__
2.
__iter__:
StopIteration
错误时退出。3.
__getitem__:
4.
__getattr__:
score
属性外,Python还有另一个机制,那就是写一个__getattr__
方法,动态返回一个属性。class Student(object):
def __init__(self):
self.name = ‘Michael‘
def __getattr__(self, attr):
if attr = ‘score‘:
return 99
5.
__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
六、使用元类
1. type()
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))
2. metaclass
上一篇:八进制转二进制 C++实现
下一篇:C++基类的继承和多态
文章标题:Python面向对象高级编程(__slots__、多继承、定制类)-6
文章链接:http://soscw.com/index.php/essay/54785.html