gpt4 book ai didi

python - python中的不可继承方法

转载 作者:行者123 更新时间:2023-12-05 04:55:06 26 4
gpt4 key购买 nike

假设我有两个类,一个继承自另一个:

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'

最佳答案

据我所知,在 Python 中没有内置的方法来执行此操作,因为它并没有真正被视为 Python 哲学的一部分。可以通过在 Python 中添加单个 _ 或双 __ 来定义“ protected ”和“私有(private)”方法,但您仍然可以调用它们,只是不鼓励这样做。

实现类似功能的一种非常 hacky 的方法可能是使方法本身成为“私有(private)”并让 __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)

但这仍然可以通过直接调用“私有(private)”方法作为 _A__doSomething 或覆盖 B 中的 __getattr__ 来规避。

或者,您还可以将检查添加到 doSomething 本身,这可能更安全也可能更简单(但恕我直言,仍然很老套)。

    def doSomething(self):
if type(self) != A:
raise TypeError("Nope")
print('It Works !')

关于python - python中的不可继承方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65584745/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com