[英]inheritance using parent class method without calling parent class
Is there any way to access parent class method, without actually calling the class? 有什么方法可以访问父类方法,而无需实际调用该类?
eg: 例如:
1) 1)
class A():
def __init__(self):
print('A class')
def name():
print('name from A class')
2) 2)
class B(A):
# I want to make use of name without actually calling or running A.
# Is there any way to do that?
Yeah, you can just call it directly. 是的,您可以直接调用它。 This works fine:
这工作正常:
class A():
def __init__(self):
print('A class')
def name(self):
print('name from A class')
class B(A):
pass
B().name()
> A class
> name from A class
You can also use it inside of the class, like 您也可以在课程内部使用它,例如
class B(A):
def b_name(self):
print('I am B!')
self.name()
If what you're trying to get around is calling A's init
, then maybe you should turn name
into a classmethod: 如果您要解决的问题是调用A的
init
,那么也许您应该将name
转换为classmethod:
class A():
def __init__(self):
print('A class')
@classmethod
def name(self):
print('name from A class')
A.name()
> name from A class
Alternatively, you can give B an init
which doesn't call its super class, thus instantiating it without calling A's init. 或者,你可以给B中的
init
不调用父类,从而实例化时不调用A的初始化。 I don't particularly recommend this method: 我不特别推荐这种方法:
class A():
def __init__(self):
print('A class')
def name(self):
print('name from A class')
class B(A):
def __init__(self):
print('B class')
def b_name(self):
print('b_name from B class')
self.name()
B().b_name()
> B class
> b_name from B class
> name from A class
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.