python 中继承的 class 属性的未定义错误
undefined error for inherited class attributes in python
我创建了一个 class workingstudent 继承自 class student 但继承的属性(姓名、学校)被程序视为未定义
class Student:
def __init__(self, name, school):
self.name = name
self.school = school
self.marks = []
def average(self):
total = sum(self.marks)
ItemNo = len(self.marks)
ave = (total / ItemNo)
print(ave)
def friend(self, friend_name):
# return a new student called "friend_name" in the same school as self
friend = Student(friend_name, self.school)
return "Anna's friend is {} and he also goes to {}".format(friend.name, self.school)
Anna = Student("Anna", "st.peters")
Anna.marks = [1, 2, 3, 5, 8]
print(Anna.name)
print(Anna.school)
print(Anna.marks)
print(len(Anna.marks))
Anna.average()
print(Anna.friend("Alex"))
class workingstudent(Student):
def __init__(self, workplace, salary):
super().__init__(name, school)
self.workplace = workplace
self.salary = salary
def get_salary(self):
return self.salary
def get_workplace(self):
return self.workplace
workingAnna = workingstudent("google", ",000")
print(workingAnna.get_salary())
print(workingAnna.get_workplace())
当代码为 运行 workingstudent class 中继承的 name 和 school 属性被视为未定义
class workingstudent(Student):
def __init__(self, workplace, salary):
super().__init__(name, school)
name
和school
这里确实没有定义。您应该将它们传递给 workingstudent.__init__
:
def __init__(self, name, school, workplace, salary):
然后
working_student = workingstudent('name', 'school', 'workplace', 999)
顺便说一句,根据 PEP8 约定,class 名称应为 WorkingStudent
。
我创建了一个 class workingstudent 继承自 class student 但继承的属性(姓名、学校)被程序视为未定义
class Student:
def __init__(self, name, school):
self.name = name
self.school = school
self.marks = []
def average(self):
total = sum(self.marks)
ItemNo = len(self.marks)
ave = (total / ItemNo)
print(ave)
def friend(self, friend_name):
# return a new student called "friend_name" in the same school as self
friend = Student(friend_name, self.school)
return "Anna's friend is {} and he also goes to {}".format(friend.name, self.school)
Anna = Student("Anna", "st.peters")
Anna.marks = [1, 2, 3, 5, 8]
print(Anna.name)
print(Anna.school)
print(Anna.marks)
print(len(Anna.marks))
Anna.average()
print(Anna.friend("Alex"))
class workingstudent(Student):
def __init__(self, workplace, salary):
super().__init__(name, school)
self.workplace = workplace
self.salary = salary
def get_salary(self):
return self.salary
def get_workplace(self):
return self.workplace
workingAnna = workingstudent("google", ",000")
print(workingAnna.get_salary())
print(workingAnna.get_workplace())
当代码为 运行 workingstudent class 中继承的 name 和 school 属性被视为未定义
class workingstudent(Student):
def __init__(self, workplace, salary):
super().__init__(name, school)
name
和school
这里确实没有定义。您应该将它们传递给 workingstudent.__init__
:
def __init__(self, name, school, workplace, salary):
然后
working_student = workingstudent('name', 'school', 'workplace', 999)
顺便说一句,根据 PEP8 约定,class 名称应为 WorkingStudent
。