![](/img/trans.png)
[英]Why can you add an attribute to an instance of a subclass of object, but not to an instance of object?
[英]How can I add an instance attribute in subclass?
這是我的代碼:
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
我想在Student類中添加一個class
實例屬性,如果我不想重寫__init__()
方法,該如何在Student類代碼中進行處理?
您不需要重寫__init__
。 假設你想Person
的__init__
功能來創建實例時被調用Student
,你可以使用super
里面的關鍵字__init__
功能的Student
:
class Student(Person):
def __init__(self):
super().__init__() # python3.0+
self.classAndGrade = ...
...
如果您使用的是python <3.0,則可以使用
super(Person, self).__init__()
這是最簡單的方法。
要添加到COLDSPEED,您還可以使用以下內容添加屬性:
class Student(Person):
def __init__(self, name, classAndGrade):
Person.__init__(self, name)
self.classAndGrade = classAndGrade
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.