python的构造函数

https://www.cnblogs.com/chaoguo1234/p/9351951.html
Python中的构造函数
Python中的构造函数是__init__函数。在Python中,子类如果定义了构造函数,而没有调用父类的,那么Python不会自动调用,也就是说父类的构造函数不会执行。

比如有test.py的module文件:

复制代码
class A:
def init(self, name):
self.name = name

class B(A):
def init(self, age):
self.age = age
复制代码
子类B继承自A,但是子类B的构造函数没有调用A的构造函数。下面我们这样测试:

复制代码

import test

b = test.B(15)
b.age
15

b.name
AttributeError: ‘B’ object has no attribute ‘name’
复制代码
由于B没有调用A的构造函数,因此,实例b上面也没有属性name,造成访问出错。

发布了25 篇原创文章 · 获赞 0 · 访问量 385

猜你喜欢

转载自blog.csdn.net/qq_45371603/article/details/104593764
今日推荐