python中的不可继承方法

python中的不可继承方法,python,inheritance,python-3.9,Python,Inheritance,Python 3.9,假设我有两个类,一个从另一个继承: class A(): 定义初始化(自): 通过 def剂量测定(自身): 打印('It Works!')#在此处插入实际代码 B(A)类: 通过 如何使doSomething方法无法继承,以便: (我希望使错误发生) >a=a() >>>a.doSomething() “它起作用了!” >>>b=b() >>>b.doSomething() 回溯(最近一次呼叫最后一次): 文件“”,第1行,在 b、 doSomething() AttributeError:

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

class A():
定义初始化(自):
通过
def剂量测定(自身):
打印('It Works!')#在此处插入实际代码
B(A)类:
通过
如何使
doSomething
方法无法继承,以便: (我希望使错误发生)

>a=a()
>>>a.doSomething()
“它起作用了!”
>>>b=b()
>>>b.doSomething()
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
b、 doSomething()
AttributeError:“B”对象没有属性“doSomething”

据我所知,Python中没有内置的方法来实现这一点,因为它实际上并不被认为是Python哲学的一部分。Python中可以通过在单个
\uu
或双
\u
前面加上前缀来定义“protected”和“private”方法,但您仍然可以调用它们,这是不可取的

实现类似功能的一种非常简单的方法可能是将方法本身设置为“私有”,并将
\uuu getattr\uuuu
重定向到该方法,但前提是对象确实是
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”方法作为
\u A\u doSomething
或在
B
中覆盖
\u getattr\u\u
来避免

或者,可能更安全,也可能更简单(但仍然相当粗糙),您还可以将该检查添加到
doSomething
本身

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

首先,您应该质疑是否希望拥有不可继承的部分。更典型的做法是将
A
B
的公共部分抽象到一个公共父项中,或者使用A

如果您坚持B必须是a的子类,那么“取消继承”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的一般精神不兼容。您的代码在我的Jupyter笔记本上运行良好。你有哪一个python版本?OP的代码正在工作,但他们不想让它工作。问题不是“为什么会发生这种异常?”它实际上没有发生。问题是“我如何使这个例外发生?”
>>> 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'