python要怎样重写父类方法
发布时间:2020-08-14 12:09:27
来源:亿速云
阅读:94
作者:小新
python要怎样重写父类方法?这个问题可能是我们日常学习或工作经常见到的。希望通过这个问题能让你收获颇深。下面是小编给大家带来的参考内容,让我们一起来看看吧!
python类的继承和重写
继承父类方法
子类可以直接调用父类的方法class Person():
def __init__(self):
pass
def hello(self):
print 'hello'
class Student(Person):
def __init__(self):
pass
s = Student()
s.hello()# hello
继承父类属性
这里要注意, 如果要继承父类的属性, 一定要在子类的构造函数里调用父类的构造函数, 否则会报错无法访问, 因为父类的构造函数没有被调用, 构造函数中的属性自然也就没有被声明
python学习网,大量的免费python学习视频,欢迎在线学习!
这时如果调用父类的属性则会报错, 报错内容为Student实例没有name属性# coding=utf-8
class Person():
def __init__(self):
self.name = '小明'
self.age = 18
print('Person class init completed')