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

2024-03-28 19:55:27 发布

您现在位置: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()

Tags: nameselfforbasedefemployeecommonall
1条回答
网友
1楼 · 发布于 2024-03-28 19:55:27

请注意

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

相关问题 更多 >