如何解决python中不可继承的方法
假设我有两个类,一个继承自另一个:
class A():
def __init__(self):
pass
def doSomething(self):
print('It Works !') # Insert actual code here
class B(A):
pass
如何使 doSomething
方法无法继承,以便:
(我想要使错误发生)
>>> a = A()
>>> a.doSomething()
'It Works !'
>>> b = B()
>>> b.doSomething()
Traceback (most recent call last):
File "<pyshell#132>",line 1,in <module>
b.doSomething()
AttributeError: 'B' object has no attribute 'doSomething'
解决方法
首先,您应该质疑是否要拥有不可继承的部分。更典型的做法是将 A
和 B
的公共部分抽象为公共父级,或者使用 mixin pattern。
class Parent
def doCommonThing1
def doCommonThing2
/ \
/ \
/ \
/ \
class A class B
def doSomething def doOtherThing
如果您坚持认为 B 必须是 A 的子类,那么“取消继承”方法的唯一方法就是覆盖它以执行其他操作。例如,引发属性错误的属性实际上与缺失属性相同:
>>> class A:
... def doSomething(self):
... print("it works")
...
>>> class B(A):
... @property
... def doSomething(self):
... msg = "{!r} object has no attribute 'doSomething'"
... raise AttributeError(msg.format(type(self).__name__))
...
>>> A().doSomething()
it works
>>> hasattr(B(),"doSomething")
False
>>> B().doSomething()
...
AttributeError: 'B' object has no attribute 'doSomething'
,
据我所知,在 Python 中没有内置的方法可以做到这一点,因为它并不真正被认为是 Python 哲学的一部分。在 Python 中可以通过添加单个 _
或双 __
来定义“受保护”和“私有”方法,但您仍然可以调用它们,只是不鼓励这样做。
实现类似的一种非常hacky的方法可能是使方法本身“私有”并让__getattr__
重定向到该方法,但前提是对象确实是一个A
。
class A():
def __init__(self):
pass
def __doSomething(self):
print('It Works !')
def __getattr__(self,attr):
if attr == "doSomething":
if type(self) == A:
return self.__doSomething
else:
raise TypeError("Nope")
return super(A).__getattr__(self,attr)
但这仍然可以通过将“私有”方法直接调用为 _A__doSomething
或覆盖 __getattr__
中的 B
来规避。
或者,可能更安全,也可能更简单(但恕我直言,仍然很老套),您也可以将该检查添加到 doSomething
本身。
def doSomething(self):
if type(self) != A:
raise TypeError("Nope")
print('It Works !')
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。