Is there any way to access parent class method, without actually calling the class?
eg:
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?
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:
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. 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.