[英]How can I add an instance attribute in subclass?
This is my code: 这是我的代码:
class Person:
def __init__(self, name):
self.name = name
class Student(Person):
def register(self, school):
pass
def payfee(self, money):
pass
def chooseClassAndGrand(self, obj):
pass
class Teacher(Person):
pass
I want to add a class
instance property to the Student class, how to do with that in the Student class code, if I do not want to rewrite the __init__()
method? 我想在Student类中添加一个
class
实例属性,如果我不想重写__init__()
方法,该如何在Student类代码中进行处理?
You do not need to rewrite __init__
. 您不需要重写
__init__
。 Assuming you want Person
's __init__
functionality to be invoked when creating an instance of Student
, you may use the super
keyword inside the __init__
function of Student
: 假设你想
Person
的__init__
功能来创建实例时被调用Student
,你可以使用super
里面的关键字__init__
功能的Student
:
class Student(Person):
def __init__(self):
super().__init__() # python3.0+
self.classAndGrade = ...
...
If you're on python < 3.0, you can use 如果您使用的是python <3.0,则可以使用
super(Person, self).__init__()
This is the easiest way to do it. 这是最简单的方法。
Do add to COLDSPEED, you can also use the below to add attributes: 要添加到COLDSPEED,您还可以使用以下内容添加属性:
class Student(Person):
def __init__(self, name, classAndGrade):
Person.__init__(self, name)
self.classAndGrade = classAndGrade
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.