Python如何在子类里扩展父类的property?
《python cookbook》8.8节讨论子类扩展property时,一开始都晕了,思考了半天才勉强弄懂一点,赶快记下来。废话不多说,先上代码:
class Person:
def __init__(self, name):
self.name = name
@property
def name(self):
print("I am in the Person's name getter")
return self._name
@name.setter
def name(self, value):
print("I am in the Person's name setter")
if not isinstance(value, str):
raise TypeError('Expected a string')
self._name = value
class SubPerson(Person):
@property
def name(self):
print("I am in the SubPerson's name getter")
super().name
@name.setter
def name(self, value):
print("I am in the SubPerson's name setter")
super(SubPerson, SubPerson).name.__set__(self, value)
我知道property其实就是特殊的描述符,但是为啥在setter里面必须显式调用父类name的__set__函数呢?直接super().name = value难道不能触发__set__函数吗?试试看:
class SubPerson(Person):
@property
def name(self):
print("I am in the SubPerson's name getter")
super().name
@name.setter
def name(self, value):
print("I am in the SubPerson's name setter")
super().name = value
>>> sp = SubPerson('shy')
I am in the SubPerson's name setter
Traceback (most recent call last):
File "<pyshell#25>", line 1, in <module>
sp = SubPerson('shy')
File "<pyshell#11>", line 3, in __init__
self.name = name
File "<pyshell#24>", line 9, in name
super().name = value
AttributeError: 'super' object has no attribute 'name'
果然报错,提示super对象没有name属性,WTF!为什么可以get但是不能set?一直没有查到答案,最后help(super),才发现蛛丝马迹:
>>> help(super)
Help on class super in module builtins:
class super(object)
| super() -> same as super(__class__, <first argument>)
| super(type) -> unbound super object
| super(type, obj) -> bound super object; requires isinstance(obj, type)
| super(type, type2) -> bound super object; requires issubclass(type2, type)
| Typical use to call a cooperative superclass method:
| class C(B):
| def meth(self, arg):
| super().meth(arg)
| This works for class methods too:
| class C(B):
| @classmethod
| def cmeth(cls, arg):
| super().cmeth(arg)
|
| Methods defined here:
|
| __get__(self, instance, owner, /)
| Return an attribute of instance, which is of type owner.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| __repr__(self, /)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __self__
| the instance invoking super(); may be None
|
| __self_class__
| the type of the instance invoking super(); may be None
|
| __thisclass__
| the class invoking super()
super本身只有__getattribute__,没有__setattr__,只对获取属性做了代理。因此设置的时候,会直接设置super()对象本身的属性,所以出现如上的错误提示,因此只能够显式调用name的__set__方法。。。。
另外一个坑就是如果子类全面扩展父类的property,可以用上面的方法,但是如果只是扩展get或者set方法,就不行了,如下:
>>> class SubPerson(Person):
@property
def name(self):
print("I am in SubPerson's getter")
super().name
>>> sp = SubPerson('shy')
Traceback (most recent call last):
File "<pyshell#48>", line 1, in <module>
sp = SubPerson('shy')
File "<pyshell#11>", line 3, in __init__
self.name = name
AttributeError: can't set attribute
父类的setter方法消失了,这里比较好理解,property是描述符,是get,set,delete的集合,子类仅仅只设置了get,set和delete相当于根本没有设置。如果想要继承父类的property,只能显式的用父类的property来装饰,如下:
>>> class SubPerson(Person):
@Person.name.getter
def name(self):
print("I am in SubPerson's getter")
return super().name
>>> sp = SubPerson('shy')
I am in the Person's name setter
>>> sp.name
I am in SubPerson's getter
I am in the Person's name getter
'shy'
此时返回的name特性,其实是复制了Person.name描述符所有方法的一个新的描述符。。
扩展子类的property,需要对描述符和super的机制有比较深入的了解,现在只是模模糊糊弄了个半懂,mark在此,随时修改。
Python如何在子类里扩展父类的property?的更多相关文章
- python基础----继承与派生、组合、接口与归一化设计、抽象类、子类中调用父类方法
一.什么是继承 继承是一种创建新的类的方式,在pyth ...
- python基础之类的继承与派生、组合、接口与归一化设计、抽象类、子类中调用父类方法
一.什么是继承 继承是一种创建新的类的方式,新建的类可以继承自一个或者多个父类,原始类称为基类或超类,新建的类称为派生类或子类. 派生:子类继承了父类的属性,然后衍生出自己新的属性,如果子类衍生出的新 ...
- Python 在子类中调用父类方法详解(单继承、多层继承、多重继承)
Python 在子类中调用父类方法详解(单继承.多层继承.多重继承) by:授客 QQ:1033553122 测试环境: win7 64位 Python版本:Python 3.3.5 代码实践 ...
- Python之面向对象的组合、多态、菱形问题、子类中重用父类的两种方式
一.组合 ''' 1.什么是组合 组合就是一个类的对象具备某一个属性,该属性的值是指向另外一个类的对象 2.为何用组合 组合也是用来解决类与类直接代码冗余问题的 3.如何用组合 ''' # 继承减少代 ...
- js扩展父类方法
在网上找了很多一直没找到关于JS扩展父类的方法,让我很是郁闷啊~要是真的开发组遇到了该咋整,于是乎自己手写了一些测试代码,没想到通过了……(难道是人品太好了?)废话不多说了直接上代码看看~ <s ...
- [面向对象之继承应用(在子类派生重用父类功能(super),继承实现原理(继承顺序、菱形问题、继承原理、Mixins机制),组合]
[面向对象之继承应用(在子类派生重用父类功能(super),继承实现原理(继承顺序.菱形问题.继承原理.Mixins机制),组合] 继承应用 类与类之间的继承指的是什么'是'什么的关系(比如人类,猪类 ...
- Odoo(OpenERP) 多个子类重载同一个父类方法的执行顺序及如何调用父类的父类方法
首先说下起因,在修改英国会计模块(没错,就是那个安格鲁撒克逊记账模式!)中不符合中国国情的部分供能时,碰到了一个棘手的问题,简单的说就是B类继承它的父类A并重载了A的方法M,同时C类也继承了A类也重载 ...
- java 子类强转父类 父类强转子类
Java 继承 继承就是子类继承父类的特征和行为,使得子类对象(实例)具有父类的实例域和方法,或子类从父类继承方法,使得子类具有父类相同的行为. Java 子类强转父类 父类引用指向子类对象: jav ...
- 子类中执行父类的方法(引出super()与mro列表)
1. 我们先想一下在python中如果子类方法中想执行父类的方法,有什么方式?大概有三种: Parent.__init__(self, name) # 通过父类的名字,指定调用父类的方法 super( ...
随机推荐
- [C#] 等待启动的进程执行完毕
有能有时候我们启动了一个进程,必须等到此进程执行完毕,或是,一段时间, 关闭进程后再继续往下走. Example sample1 等待应用程序执行完毕 //等待应用程序执行完毕 private voi ...
- In function 'int av_clipl_int32_c(int64_t)': error: 'UINT64_C' was not declared in this scope
cygwin下使用ndk编译jni时遇到的错误: /ffmpeg/include/libavutil/common.h: In function 'int av_clipl_int32_c(int64 ...
- string的深入理解
本文只是个人总结见解,勿喷 首先肯定的是string是引用类型 string s_a = "yhc"; string s_b = s_a; if(s_a.Equals(s_b)) ...
- 6410在rvds下编译启动代码报错分析
contains invalid call from '~PRES8' function to 'REQ8' function main RVDS编译出现contains invalid call f ...
- laravel中间键组
` php artisan make:middleware Lend这边我定义一个登陆的中间件这边要注意的就是,当条件成立的时候一定要 return $next($request);不写这个larav ...
- laravel 验证表单信息
1控制器验证 $this->validate($request,[ 'Student.name'=>'required|min:2|max:20', 'Student.age'=>' ...
- 【SQL Server数据迁移】把csv文件中的数据导入SQL Server的方法
[sql] view plaincopy --1.修改系统参数 --修改高级参数 sp_configure 'show advanced options',1 go --允许即席分布式查询 sp_co ...
- 17-pow(c++)
C++中有封装的pow()可以直接调用,头文件math,同时对函数进行了重载,支持多种参数格式: double pow (double base , double exponent); float p ...
- 关于ptrdiff_t
整除.opencv中的内存一般是通过malloc分配,不能保证都是都能被16整除,此时需要截断,但是剩下的内存要如何维护? CV2.0的这样维护的:在 malloc 是多申请一个指针的空间,这个指针指 ...
- 2、python的print函数格式化输出
1.格式化输出浮点数(float) pi = 3.141592653 print('%10.3f' % pi) #字段宽10,精度3 ,结果 print('%010.3f' % pi) #用0填充 ...