我正在学习python,我正在尝试将值从输入传递给我写的模块的args,但我不知道如何开始。
有人可以给我一些建议吗?
这是我正在调用的模块
#!/usr/bin/python
class Employee:
'Practice class'
empCount = 0
def __init__(self, salary):
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print "Total Employees %d" % Employee.empCount
def displayEmployee(self):
print "Salary: ", self.salary
class Att(Employee):
'Defines attributes for Employees'
def __init__(self, Age, Name, Sex):
self.Age = Age
self.Name = Name
self.Sex = Sex
def display(self):
print "Name: ", self.Name + "\nAge: ", self.Age, "\nSex: ", self.Sex
这是我用于调用并将值传递给上述模块中的args的代码
#!/usr/bin/python
import Employee
def Collection1():
while True:
Employee.Age = int(raw_input("How old are you? "))
if Employee.Age == str(Employee.Age):
print "You entered " + Employee.Age + " Please enter a number"
elif Employee.Age > 10:
break
elif Employee.Age > 100:
print "Please enter a sensible age"
else:
print "Please enter an age greater than 10"
return str(Employee.Age)
def Collection2():
Employee.Name = raw_input("What is your name? ")
return Employee.Name
def Collection3():
while True:
Employee.Sex = str(raw_input("Are you a man or a woman? "))
if Employee.Sex == "man":
Employee.Sex = "man"
return Employee.Sex
break
elif Employee.Sex == "woman":
Employee.Sex = "woman"
return Employee.Sex
break
else:
print "Please enter man or woman "
Attributes = Employee.Employee()
Collection1()
Collection2()
Collection3()
Attributes.displayEmployee()
我猜我需要从用户那里获取输入并将其放在类的变量中。我试过了,但我猜我做错了什么?
答案 0 :(得分:1)
Employee.Age = int(raw_input("How old are you? "))
在模块中设置变量而不是使用局部变量,设置在外面 Collection1()函数是没有用的。请注意,您不设置employee(object)属性',但是模块 - 这可能不是您想要的。此外,按照惯例,函数应以初始小写命名。
你的继承模型有点奇怪。为什么员工属于不同的(子)类?通常,属性进入主类构造函数。如果您确实想要为属性使用单独的类,则在这种情况下根本不应使用子类。
修改强> 这就是我认为你打算做的事情:
#!/usr/bin/python
class Employee:
def __init__(self, salary, age, name, sex):
self.salary = salary
self.age= age
self.name= name
self.sex= sex
#Employee.empCount += 1 #don't do this. you should count instances OUTSIDE
def __str__(self):
return "Employee<Name: {0}, Age: {1}, Sex: {2}, Salary: {3}>".format( self.name, self.age, self.sex, self.salary)
def getAge():
while True:
try:
s=raw_input("How old are you? ")
age = int(s)
if age > 100:
print "Please enter a sensible age"
elif age<=10:
print "Please enter an age greater than 10"
else:
return age
except ValueError:
print "You entered " + s + " Please enter a number"
def getName():
return raw_input("What is your name? ")
def getSex():
while True:
sex = str(raw_input("Are you a man or a woman? "))
if not sex in ("man", "woman"):
print "Please enter man or woman "
else:
return sex
age= getAge()
name= getName()
sex= getSex()
salary=100000
employee = Employee(salary, age, name, sex)
print employee
如果您希望Employee位于不同的文件(模块)中,只需将其放在那里并从主代码运行from Employee import Employee
(第一个是模块,第二个是类)。