我想在另一个函数中调用类的函数,但我尝试了所有方法仍然有错误

时间:2015-04-17 17:07:08

标签: python

class Employee:    

    'Common base class for all employees'
    empCount = 0
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary
        Employee.empCount += 1
    def displayCount(self):
        print "Total Employee %d" % Employee.empCount
    def displayEmployee(self):
        print "Name : ", self.name,
        ", Salary: ", self.salary
        self.displaycount()


emp1 = Employee("Zara", 2000)

emp1.displayEmployee()

1 个答案:

答案 0 :(得分:3)

请注意

print "Name : ", self.name,
", Salary: ", self.salary
self.displaycount()

被解释为三条逻辑行:

print "Name : ", self.name,  # print two things, suppress the newline
", Salary: ", self.salary  # this makes no sense - tuple? Gets ignored
self.displaycount()  # call a method - but Python is case sensitive!

Python不会隐式地继续逻辑行。您可以为显式延续添加反斜杠:

print "Name : ", self.name, \
", Salary: ", self.salary

但我认为使用正确的string formatting

会好得多
print "Name: {0.name}, Salary: {0.salary:.02f}".format(self)

你还需要使用正确的案例来访问方法(Python是区分大小写的),所以它应该是:

self.displayCount()
          # ^ note

或者,根据the style guide,将其命名为display_count