我正在尝试构建一个程序,该程序将询问有多少人,为每个人创建一个对象,并从用户那里获取每个对象的单独信息(例如名称,每周工作时间,工资)。这样,我可以简单地输入有关员工的信息,而不同的功能可以为每个员工计算薪水。
到目前为止,我只能为每个人创建两个单独的对象和类,并且必须手动添加每个人才能执行多个操作。截至目前,这只允许我有2个人。我想问用户有多少人,然后为每个对象有一个自己的变量/信息。
class SalesPerson1:
def __init__(self, name1 = '', weeklyhrs1 = 0, wage1 = 0):
self.name1 = input('Enter the first employees name?')
self.weeklyhrs1 = input('Enter the first employees number of weekly hours?')
self.wage1 = input('Enter the first employees weekly wage?')
def salesPerson1(self):
return self.name1
return self.weeklyhrs1
return self.wage1
class SalesPerson2:
def __init__(self, name2 = '', weeklyhrs2 = 0, wage2 = 0):
self.name2 = input('Enter the second employees name?')
self.weeklyhrs2 = input('Enter the second employees number of weekly hours?')
self.wage2 = input('Enter the second employees weekly wage?')
def salesPerson2(self):
return self.name2
return self.weeklyhrs2
return self.wage2
person1 = SalesPerson1()
person2 = SalesPerson2()
答案 0 :(得分:0)
您似乎需要阅读python类。文件是here
类实例化使用函数符号。只是假装 类对象是返回新实例的无参数函数 班上的例如(假设上面的类):
x = MyClass()
创建该类的 新实例 ,并将该对象分配给 局部变量x。
答案 1 :(得分:0)
只是一个例子,但是您可以创建一个通用类并使用该类进行处理,而不用为其他人创建不同的类
class SalesPerson:
def __init__(self):
self.name1 = []
self.weeklyhrs1 = []
self.wage1 =[]
def add_name(self,name):
self.name1.append(name)
def add_weeklyhrs(self,weeklyhrs):
self.weeklyhrs1.append(weeklyhrs)
def add_wage(self,wage):
self.wage1.append(wage)
def show_name(self):
return self.name1
def show_weeklyhrs1(self):
return self.weeklyhrs1
def show_wage1(self):
return self.wage1
t = int(input('no of person you want to take input : '))
x=SalesPerson()
for i in range(t):
print("enter details for {} person".format(i+1))
x.add_name(input('enter name '))
x.add_weeklyhrs(input('enter hours '))
x.add_wage(input('enter wage '))
答案 2 :(得分:0)
您应该创建一个类并使用循环来运行input()
并创建该类的实例并添加到列表中
class SalesPerson:
def __init__(self, name='', weeklyhrs=0, wage=0):
self.name = name
self.weeklyhrs = weeklyhrs
self.wage = wage
def get(self):
return self.name, self.weeklyhrs, self.wage
# list to keep all persons
all_persons = []
# get all persons
how_many = input('How many persons?')
for x in range(how_many):
a = input('Enter the first employees name?')
b = input('Enter the first employees number of weekly hours?')
c = input('Enter the first employees weekly wage?')
person = SalesPerson(a, b, c)
all_persons.append(person)
# display all persons
for person in all_persons:
print(person.get())