我正在尝试按照Python教程让用户输入变量,然后我的类将根据输入的内容输出它。教程硬编码值,我可以让它工作,但我试图进入下一步,让他们输入值并使用它们。到目前为止,所有代码都是让它们输入值,而不是将它们发布到输出中。下面是两组代码
这是我正在使用的教程中的代码:(可以在这里找到:http://www.tutorialspoint.com/python/python_classes_objects.htm
)
#!/usr/bin/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
"This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount
这是我的代码
class People:
personName = input('Enter your name: ')
personAge = input('Enter your age: ')
def __init__(self, personName, personAge):
self.personName = personName
self.personAge = personAge
def displayPerson(self):
print "Name : ", self.personName, ", Age: ", self.personAge
person1 = People(personName, personAge)
person1.displayPerson()
答案 0 :(得分:0)
你在错误的地方做这件事。你需要在课外进行,在你实例化的时候:
personName = raw_input('Enter your name: ')
personAge = raw_input('Enter your age: ')
person1 = People(personName, personAge)
person1.displayPerson()
请注意,由于这似乎是Python 2.7,因此您应该使用raw_input
而不是input
。您还应该从object
继承您的课程。
答案 1 :(得分:0)
您应该将输入代码移出类声明,就像这样。
class People:
def __init__(self, personName, personAge):
self.personName = personName
self.personAge = personAge
def displayPerson(self):
print "Name : ", self.personName, ", Age: ", self.personAge
personName = input('Enter your name: ')
personAge = input('Enter your age: ')
person1 = People(personName, personAge)
person1.displayPerson()