国企门户网站建设方案,深圳网络运营推广公司,电商网站对比表格,服务好质量好的网站制作#问题描述
在学习别人的code的时候#xff0c;往往存在子类和父类#xff0c;发现子类和父类存在同名函数#xff0c;并且父类中改该方法是异常触发#xff0c;如果子类的该方法有具体的执行内容的话#xff0c; 其实是可以执行子类的方法#xff0c;而不执行父类方法。…#问题描述
在学习别人的code的时候往往存在子类和父类发现子类和父类存在同名函数并且父类中改该方法是异常触发如果子类的该方法有具体的执行内容的话 其实是可以执行子类的方法而不执行父类方法。具体例子
# 在这种情况下子类 Child 提供了自己的 my_function 实现该实现会覆盖父类# 的函数并且不会触发异常。
class Parent:def my_function(self):raise NotImplementedError(This function is not implemented in the parent class)class Child(Parent):def my_function(self):return Custom implementation in the child classchild_instance Child()
result child_instance.my_function() # 这会调用子类的自定义实现
print(result) # 输出: Custom implementation in the child class