python abstractmethod,Python使用abstractmethod的不同行为

I have two classes inheriting from the same parent P:

from abc import ABCMeta, abstractmethod

class P(object):

__metaclass__ = ABCMeta

@abstractmethod

def foo(self):

pass

class C(P):

pass

class D(tuple, P):

pass

The only difference is that D inherited from tuple and P while C inherits from P only.

Now this is the behavior: c = C() got error, as expected:

TypeError: Can't instantiate abstract class C with abstract methods foo

but d = D() works without error!

I can even call d.foo(). How can I explain this behaviour?

解决方案

Abstract methods are tested for in the object.__new__ method; when you inherit from tuple, which has its own __new__ method, object.__new__ is not called and the test for abstract methods is not made.

In other words, mixing abstract methods with any of the built-in immutable types will cause this problem.

The only solution that works is to do your own test in __new__ and then only if you put your abstract class before tuple when mixing in the two bases in a subclass.

class P(object):

__metaclass__ = ABCMeta

def __new__(cls, *args, **kwargs):

super_new = super(P, cls).__new__

if super_new.__self__ is not object:

# immutable mix-in used, test for abstract methods

if getattr(cls, '__abstractmethods__'):

raise TypeError(

"Can't instantiate abstract class %s "

"with abstract methods %s" % (

cls.__name__,

', '.join(sorted(cls.__abstractmethods__))))

return super_new(cls, *args, **kwargs)

@abstractmethod

def foo(self):

pass

class D(P, tuple):

pass

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值