
子类访问父类的函数python
常见问答
子类如何调用父类中的方法?
在Python中,想要在子类中使用父类定义的方法,应该采用什么方式?
使用super()函数调用父类方法
在子类中,可以使用super()函数来调用父类中的方法。示例代码如下:
class Parent:
def greet(self):
print('Hello from Parent')
class Child(Parent):
def greet(self):
super().greet() # 调用父类方法
print('Hello from Child')
c = Child()
c.greet()
执行结果为:
Hello from Parent
Hello from Child
有没有不使用super()的方式让子类访问父类函数?
除了super()函数,是否还有其他方法可以实现子类调用父类的方法?
通过父类名直接调用父类方法
可以直接通过父类的名字调用其方法,并将子类实例(self)作为参数传入。例如:
class Parent:
def greet(self):
print('Hi from Parent')
class Child(Parent):
def greet(self):
Parent.greet(self) # 直接调用父类方法
print('Hi from Child')
c = Child()
c.greet()
这样也能实现调用父类函数的效果。
子类访问父类私有方法是否可行?
如果父类中有私有方法,子类能直接访问或调用这些方法吗?
子类不能直接访问父类的私有方法
Python中,私有方法名通常以双下划线开头,例如__private_func。这种名称会进行名称改编(Name Mangling),使得子类无法直接访问。若需要在子类中使用,建议父类将其定义为保护成员(单下划线开头)或者提供公共接口方法,子类通过调用公共接口间接访问私有功能。