【问题标题】:Trouble understanding with getting a unique instantiation in Python难以理解在 Python 中获得唯一的实例化
【发布时间】:2014-03-28 15:01:57
【问题描述】:

我有一个员工类,它有一个从文件中读取员工记录的 init 方法。我还有一个员工类,它有一个尝试读取所有员工记录的 init_ 方法。

我在员工类的 init 方面遇到问题。这是我的代码:

class EmployeeList():
      records=[]
      def __init__(self):
          with open(database) as fp:
              emp=employee(fp)
              while (emp.id > 0):
                    print(emp)
                    self.records.append(emp)
                    emp=employee(fp)

print(emp) 用于错误检查,它表明记录正在被正确读取。当到达 EOF 时,员工的 init 方法将 id 设置为 0,将员工的名称设置为 ""。我有两个问题:

  1. 循环之后,employees.records 中的所有员工都相同 - id 为 0,名称为空白。我假设 emp 每次调用时都不会创建一个新实例,因此所有员工都被设置为一个 emp 实例,即到达 EOF 时的最后一个实例。

    李>
  2. 我怀疑我的代码是“Pythonesque”;欢迎提出改进建议。

附:数据库被全局定义为文件名。

完整的代码在这里,关于长度抱歉:

class employee:
    count = 0
    def __init__(self,f=None):
        if (f==None): # a user is inputting the employee
           self.lastname = input("Employees last name:")
           while type(self.lastname)!=type("1"):
                 print("Your input needs to be a name\n")
                 self.lastname = input("Employees last name:")
           self.firstname = input("Employees first name:")
           while type(self.firstname)!=type("1"):
                  print("Your input needs to be a name\n")
                  self.firstname = input("Employees first name:")
           self.payrate = float(input("Employees pay rate:"))
           while type(self.payrate)!=type(0.0):
                  print("Your input needs to be a pay rate\n")
                  self.payrate = float(input("Employees pay rate:"))
           employee.count = employee.count + 1
           self.id = employee.count
        else: # the employee is being read in from the database and f is a file pointer
              # read in an employee record and return false for end of file.
           checkEOF = f.readline().rstrip('\r\n') #check for end of file
           if (checkEOF != ""):
               employee.id = int(checkEOF)
               employee.firstname = f.readline().rstrip('\r\n')
               employee.lastname = f.readline().rstrip('\r\n')
               employee.payrate = float(f.readline().rstrip('\r\n'))
           else:
               employee.id = 0
               employee.firstname = " "
               employee.lastname = " "
               employee.payrate = 0.0
    def __hash__(self):
        return hash(self.id)
    def __eq__(self, other):
        if isinstance(other, self.__class__):
            return self.id == other.id
        return NotImplemented
    def __str__(self):
        return "Employee " + str(self.id) + " is "+self.firstname + " "+self.lastname+" and their pay rate is "+str(self.payrate)+"\n"
    def __lt__(self, other):
        if (self.lastname < other.lastname):
           return True
        elif (self.lastname > other.lastname):
           return False
        else: #same last names
           if (self.firstname < other.firstname):
              return True
           elif (self.firstname > other.firstname):
              return False
           else: #same names
             if (self.id < other.id):
                return True
             else: # note that ids cannot be the same
                return False
    def __gt__(self, other):
        if (self.lastname > other.lastname):
           return True
        elif (self.lastname < other.lastname):
           return False
        else: # Same last names
           if (self.firstname > other.firstname):
              return True
           elif (self.firstname > other.firstname):
              return False
           else: # Same names
             if (self.id > other.id):
                return True
             else: # note that ids cannot be the same
                return False
    def payraise(self,payraise):
        self.payrate = self.payrate+payraise
    def saveemployee(self,fp):
        fp.write(str(self.id)+"\n")
        fp.write(self.firstname+"\n")
        fp.write(self.lastname+"\n")
        fp.write(str(self.payrate)+"\n")

class EmployeeList():
    records=[]
    def __init__(self):
        with open(database) as fp:
             emp=employee(fp)
             while (emp.id > 0):
                   print(emp)
                   self.records.append(emp)
                   emp=employee(fp)
    def __str__(self):
        employeesprint = ""
        for emp in self.records:
            employeesprint = employeesprint + str(emp)
        return employeesprint
    def save(self):
        self.records.sort()
        with open(database,"w+") as fp:
             fp.seek(0)
             for emp in self.records:
                   emp.saveemployee(fp)
def menu():
    print("\n")
    print(choices[0]+". Add another employee")
    print(choices[1]+". Print employees")
    print(choices[len(choices)-1]+". Quit")
    print("\n")

employees = EmployeeList()
choices = ["A","B","C"]
ch = "N"
while (ch != choices[len(choices)-1]):
    menu()
    ch=input("Make your choice ")
    while not (ch in choices):
        menu()
        ch=input("Make your choice ")
    if (ch == choices[0]):
        employees.records.append(employee())
        employees.save()
    if (ch == choices[1]):
        print(employees)

示例输出:您可以看到两个员工在读入时被正确打印:

员工 1 是简·鲍勃,他们的工资率为 1.0

员工 2 是 jim bob,他们的工资率为 3.4

A.添加其他员工

B.打印员工

C.退出

做出你的选择

员工 0 是,他们的工资率是 0.0

员工 0 是,他们的工资率是 0.0

【问题讨论】:

  • 那么让我们看看Employee类__init__代码...
  • 要使代码更“Pythonesque”,请使用= - records = []emp = employee(fp) 周围的空格。请参阅 PEP8 中的 Whitespace in Expressions and Statements
  • 贴出代码,否则我们帮不了你。

标签: python class instantiation


【解决方案1】:

你的代码:

       if (checkEOF != ""):
           employee.id = int(checkEOF)
           employee.firstname = f.readline().rstrip('\r\n')
           employee.lastname = f.readline().rstrip('\r\n')
           employee.payrate = float(f.readline().rstrip('\r\n'))
       else:
           employee.id = 0
           employee.firstname = " "
           employee.lastname = " "
           employee.payrate = 0.0

把'employee'改成'self','employee'是班级的名字。

【讨论】:

  • 哦,天哪。我认为这可能是愚蠢的,但那很糟糕。无法告诉你我看了多少次代码却没有看到。谢谢!!!!
  • @user3353877 这是将类名和小写实例名大写的一个很好的理由,如果您正在寻找一个 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-02
  • 1970-01-01
  • 2018-07-31
  • 2021-12-05
相关资源
最近更新 更多