[英]How to inherit all class attributes, but one? Python
How to inherit all class 'A' attributes and methods, but 'b()'?如何继承所有 class 'A' 属性和方法,但 'b()'?
class A:
def __init__(self):
# attributes
pass
@classmethod
def b(cls):
# logic
pass
class B(A):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def b(self):
# nothing
pass
do not use this old method( if there is another way to do it ):不要使用这种旧方法(如果有其他方法):
class B(A):
def __init__(self, attributes):
super().__init__(self, attributes)
You can reimplement b()
to raise an error:您可以重新实现
b()
以引发错误:
class A:
def __init__(self):
# attributes
pass
@classmethod
def b(cls):
# logic
pass
class B(A):
def __init__(self, **kwargs):
super().__init__(**kwargs)
@classmethod
def b(cls):
raise TypeError("method b is not supported in class B")
Also, if b()
is a classmethod
, you should probably override it as a classmethod
.此外,如果
b()
是一个classmethod
,您可能应该将它覆盖为一个classmethod
。
Put that method in a separate class and don't inherit it.将该方法放在单独的 class 中,不要继承它。
class A:
def __init__(self):
# attributes
pass
class A1:
@classmethod
def b(cls):
# logic
pass
class B(A):
def __init__(self, **kwargs):
super().__init__(**kwargs)
Use multiple inheritance when you want that method.当您需要该方法时,请使用多个 inheritance。
class C(A,A1):
pass
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.