python 类的继承

假设父类:

class Parent(object):
def __init__(self):
print("打印父类")
print(__class__)
self.p_name = "父类属性"
self.p_code = "10000"
def get_parent_function(self):
print("打印父类方法")
def get_common_function(self):
print("打印公共方法")

子类:
from test_class_parent import Parent
class Child(Parent):
def __init__(self):
super(Parent, self).__init__() #子类在继承父类初始化时,如果super方法指定父类类名时,则父类的__init__()方法不会在子类的__init__()方法执行时执行,
同时子类如未定义父类的同名属性,则无法访问父类的属性,如执行结果1中:父类的self.p_code子类无法访问
        #super(Child, self).__init__() #子类在继承父类初始化时,如果super方法指定子类类名时,则父类的__init__()方法会在子类的__init__()方法执行时执行,
                                        同时子类如未定义父类的同名属性,子类仍可以访问父类的属性,如父类的self.p_code子类访问正常

print("打印子类")
print(__class__)
self.p_name = "子类属性"
def get_parent_function(self):
print("打印子类方法")
if __name__ == '__main__':
child = Child()
child.get_parent_function()
child.get_common_function()
print(child.p_code)

执行子类结果1如下:

G:\pyt\venv\Scripts\python.exe G:/test_app/test_class_child.py
打印子类
<class '__main__.Child'>
打印子类方法
打印公共方法
Traceback (most recent call last):
File "G:/test_app/test_class_child.py", line 25, in <module>
print(child.p_code)
AttributeError: 'Child' object has no attribute 'p_code'

Process finished with exit code 1

执行子类结果2如下:

G:\pyt\venv\Scripts\python.exe G:/test_app/test_class_child.py
打印父类
<class 'test_class_parent.Parent'>
打印子类
<class '__main__.Child'>
打印子类方法
打印公共方法
10000

Process finished with exit code 0

 

posted @   遇事不决,量子力学  阅读(12)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示