[英]AttributeError: type object 'Student' has no attribute 'name'
[英]AttributeError: type object 'Student' has no attribute 'gpa'
我目前遇到此錯誤的問題: AttributeError: type object 'Student' has no attribute 'gpa'
當我嘗試運行以下程序時。
class people(object):
def __init__(self,name,ID):
self.name=name
self.ID=ID
class Student(people):
def __init__(self,name,ID,gpa):
self.name=name
self.ID=ID
self.gpa=gpa
Student.gpa.total.append(self.gpa)
def mean_gpa():
return sum(Student.gpa_total)/float (len(Student.gpa_total))
def info_gpa(self):
mean= self.mean_gpa()
return mean
def __str__(self):
return self.info_gpa()
class Employee(people):
def __init__(self,name,ID,salary):
people._init_(self,name,ID)`
self.name=name
self.ID=ID
self.salary=salary
self.employee=employee
Employee.emp_total.append(self.employee)`
def total_salary():
return sum(Employee.emp_total)`
任何想法我做錯了什么?
您正在嘗試在此處訪問Student.gpa
:
Student.gpa.total.append(self.gpa)
我不確定該行應該做什么,但是當它不存在時,您試圖將其作為靜態變量(類的屬性,而不是類的實例)進行訪問。 __init__()
分配一個gpa
屬性self
,這是Student
的一個實例,但這不是您要訪問的。此外, self
沒有在__init__()
之外定義。
實際上,我再次閱讀了您的代碼。 看起來你想要這樣的東西:
class Student(people):
def __init__(self,name,ID,gpa):
self.name=name
self.ID=ID
self.gpa=gpa
try:
Student.gpa_total.append(self.gpa)
except AttributeError:
Student.gpa_total=[self.gpa]
快速瀏覽pyflakes向我展示了這兩個錯誤:
第 12 行:未定義名稱self
。
提示:使用Student.gpa.total.append(self.gpa)
行,你指的是類之外的self
,所以它是未定義的。
第 29 行:未定義名稱employee
。 在Employee
類self.employee=employee
中,您已將self.employee
設置為一個不存在的名為employee
的變量
嘗試創建一個可以使用 gpa 方法的 student 實例。 IE,
student1=student("Tom",12345,3.8)
student1.gpa()
訪問實例
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.