有没有办法访问父类方法,而不实际调用类?
e.g:
1)
class A():
def __init__(self):
print('A class')
def name():
print('name from A class')
2)
class B(A):
# I want to make use of name without actually calling or running A.
# Is there any way to do that?
答案 0 :(得分:2)
是的,你可以直接调用它。这很好用:
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
你也可以在课堂内使用它,比如
class B(A):
def b_name(self):
print('I am B!')
self.name()
如果您尝试解决的问题是致电A init
,那么也许您应该将name
转变为一种类别方法:
class A():
def __init__(self):
print('A class')
@classmethod
def name(self):
print('name from A class')
A.name()
> name from A class
或者,你可以给B一个init
,它不会调用它的超类,因此在不调用A的初始化的情况下实例化它。我不特别推荐这种方法:
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