2014-12-15 4 views
0

나는 어디에서나 연구했지만 동일한 개념을 발견했지만 오류에 대한 답을 찾지 못하는 것 같습니다.언 바운드 오류 파이썬 클래스

내 계정 정보가 스택에서 잊어 버렸기 때문에 이전에 게시하지 못했지만이 초급 오류로 인해 매우 불만을 느꼈습니다.

class Person(object): 

    def __init__(self, name, phone): 
     self.name = name 
     self.phone = phone 

class Employee(Person): 

    total_salary = 0 

    @staticmethod 
    def total_salary(self, salary): 
     return total_salary 


    def __init__(self, name, phone, salary): 
     self.name = name 
     self.phone = phone 
     self.salary = salary 




class Student(Person): 

    def __init__(self, name, phone, gpa): 
     self.gpa = gpa 
     self.name = name 
     self.phone = phone 

    def __str__(self): 
     reply = "" 
     reply = "Person " + self.name + " has phone " + self.phone + "\n" + " and is a Student with gpa " + str(self.gpa) 
     return reply 

class Professor(Employee): 
    def __init__(self, name, phone, salary, clas_teach): 
     self.clas_teach = clas_teach 
     self.name = name 
     self.phone = phone 
     self.salary = salary 

    def __str__(self): 
     reply = "" 
     reply = "Person " + self.name + " has phone " + self.phone + "\n" + " and is an Employee with salary " + str(self.salary) + "\n" 
     reply += " and is a Professor assigned to class " + self.clas_teach 
     return reply 

class Staff(Employee): 
    def __init__(self, name, phone, salary, position): 
     self.position = position 
     self.name = name 
     self.phone = phone 
     self.salary = salary 
    def __str__(self): 
     reply = "" 
     reply = "Person " + self.name + " has phone " + self.phone + "\n" + " and is an Employee with salary " + str(self.salary) + "\n" 
     reply += " and is Staff with title " + self.position 
     return reply 
# Create a list of people 
People = [ Student("Sandy", "326-8324", 3.65), Student("Jordan", "632-7434", 3.1), \ 
      Professor("Leslie", "985-2363", 50000.00, "Info 501"), \ 
      Staff("Alex", "743-4638", 25000.00, "Editor") ] 

# display information about our people 
print "These are the people in the university:" 
for person in People: 
    print person 

# display the total salaries of all our employees and average GPA 
# of all of our students 
print 
print "Our total university payroll budget is: " + str(Employee.total_salary) 
print "Our average student GPA is: " + str(Student.mean_gpa()) 
+0

오류가 <0x02682670에서 기능 total_salary이> 지금를 사용하여 더 명확하게 할 수 있지만, @staticmethod없이 나에게 준 <언 바운드 방법을 Employee.total_salary> –

+1

당신을 결코 total_salaries 메소드에서 급여를 합하면 사용되지 않는 두 개의 매개 변수를 전달하고'total_salary'는 반환되지 않고 클래스 속성도 사용되지 않습니다. 너 뭐하려고? 이 문제를 어떻게 해결하고 싶습니까? –

+0

People에 직원의 급여를 추가하려고하지만 직원을 추가 할 때 급여가 추가되는지 확인하려고합니다. –

답변

2

가장 중요한 오해는 수업의 작동 방식입니다. 여기

print "Our total university payroll budget is: " + str(Employee.total_salary) 
print "Our average student GPA is: " + str(Student.mean_gpa()) 

중요한 것입니다 : 당신의 코드에서 클래스의 클래스가 아닌 인스턴스를 호출

대신에이 같은 일을해야
Employee.total_salary 

:

leslie = Professor("Leslie", "985-2363", 50000.00, "Info 501") 
print "Leslie's Salary: " + str(leslie.salary) 

을 이 경우, 모든 급여의 합계 인 총 급여를 원하게됩니다. 어딘가에 직원들의 모임이 필요합니다. 등 betweeen 직원과 학생, 정렬과 같은 당신이해야 더 많은 조정이있다, 분명히

university = University() 
university.add_employee(Professor("Leslie", "985-2363", 50000.00, "Info 501")) 
university.add_employee(Staff("Alex", "743-4638", 25000.00, "Editor")) 

print "Total payroll: " + str(university.get_total_payroll()) 

그러나 희망이 충분하다 :

def University(): 
    def __init__(self): 
     self.employees[] 

    def add_employee(self, employee): 
     self.employees.append(employee) 

    def get_total_payroll(self): 
     total = 0 
     for employee in self.employees: 
      total += employee.salary 
     return total 

는 해당 클래스의 인스턴스를 사용 너 시작 했어.

0

이 다른 답변에 포함 된 전체 디자인에 문제가있다, 그래서 당신의 현재 코드가 작동하지 않는 이유를 설명하려고합니다 : 당신은 total_salary라는 이름의 클래스 속성을 만든

  1. 하고, 그 다음에 같은 이름의 방법으로 그림자를 그렸다.
  2. 클래스 메서드를 사용해야하는 경우 정적 메서드를 사용하고 있습니다.
  3. 값을 반환하려면 메서드로 total_salary을 호출해야합니다.

    class Employee(Person): 
        _total_salary = 0 
    
        @classmethod 
        def total_salary(cls): 
         return cls._total_salary 
    ... 
    
    print "Our total university payroll budget is: " + str(Employee.total_salary()) 
    

    을하지만 아직 정의되지 않은 Student.mean_gpa를 호출하려고하기 때문에 코드가 여전히 AttributeError을 올릴 참고 :

이러한 문제는 다음과 같이 해결할 수 있습니다.

0

클래스 직원 클래스에는 속성과 동일한 이름의 메소드가 있습니다. Employee.total_salary를 호출하면 MRO에 속성이 대체되므로 함수가 반환됩니다.

변경 : 귀하는 Employee에서 staticmethod total_salary은 (그것은 단지 방법의 범위에서 찾고 있기 때문에) 존재하지 않는 변수를 반환

class Employee(Person): 
    total_salary = 0 

class Employee(Person): 
    total_salary_value = 0 

에, 당신은 직원을 반환해야 .total_salary_value.그래서 같이 : 당신은 당신이 Student에 (같은 일을 상속하는 Person를 인스턴스화되지 Employee__init__에서

@staticmethod 
def total_salary(): 
    return Employee.total_salary_value 

(둘 Employee)

사용을 상속 (Person), ProfessorStaff을 상속 :

Person.__init__(self,name,phone) 

또는

초기화에서 여전히
super(Employee, self).__init__(name, phone) 

0, 당신은 total_salary_value

에 급여를 추가하지 않는 것은이 추가

또한
Employee.total_salary_value += self.salary 

Studentself.nameself.phone를 사용할 필요가 Person 때문에,이 없다 이미이 속성이 있습니다.

그리고 마지막으로 (즉, 다른 변수와 ProfessorStaff에 대한 동일)은 Studentmean_gpa라는 방법이 없다. 당신은 그것을 구현해야합니다.

여기에 코드입니다 :

class Person(object): 
    def __init__(self, name, phone): 
     self.name = name 
     self.phone = phone 

class Employee(Person): 
    total_salary_value = 0 

    @classmethod 
    def total_salary(cls): 
     return cls.total_salary_value 

    def __init__(self, name, phone, salary): 
     Person.__init__(self,name,phone) 
     self.salary = salary 
     Employee.total_salary_value += self.salary 

class Student(Person): 
    all_gpa = [] 

    def __init__(self, name, phone, gpa): 
     Person.__init__(self,name,phone) 
     self.gpa = gpa 
     Student.all_gpa.append(self.gpa) 

    def __str__(self): 
     return "Person {0} has phone {1} and is a Student with gpa {2}".format(self.name,self.phone,self.gpa) 

    @classmethod 
    def mean_gpa(cls): 
     return sum(cls.all_gpa)/len(cls.all_gpa) 


class Professor(Employee): 
    def __init__(self, name, phone, salary, clas_teach): 
     Employee.__init__(self,name,phone,salary) 
     self.clas_teach = clas_teach 

    def __str__(self): 
     return "Person {0} has phone {1} and is an Employee with salary {2}\n" \ 
       "and is a Professor assigned to class {3}".format(self.name,self.phone,self.salary,self.clas_teach) 


class Staff(Employee): 
    def __init__(self, name, phone, salary, position): 
     Employee.__init__(self, name, phone, salary) 
     self.position = position 

    def __str__(self): 
     return "Person {0} has phone {1} and is an Employee with salary {2}\n" \ 
       "and is Staff with title {3}".format(self.name, self.phone, self.salary, self.position) 

# Create a list of people 
People = [ Student("Sandy", "326-8324", 3.65), 
      Student("Jordan", "632-7434", 3.1), 
      Professor("Leslie", "985-2363", 50000.00, "Info 501"), 
      Staff("Alex", "743-4638", 25000.00, "Editor") ] 

# display information about our people 
print "These are the people in the university:" 
for person in People: 
    print person 

# display the total salaries of all our employees and average GPA 
# of all of our students 
print 
print "Our total university payroll budget is: " + str(Employee.total_salary()) 
print "Our average student GPA is: " + str(Student.mean_gpa()) 

편집 : @ekhumoro, 그것은 값을 반환하는 @classmethod를 사용하는 것이 좋습니다 말했듯이

.

또 다른 것은, 당신의 __str__는 .format()