[英]Getting a Python Class to display user inputted variables
I am trying to follow a Python tutorial to get a user to input variables and then my class will output it depending on what they inputted. 我正在尝试遵循Python教程来让用户输入变量,然后我的课程将根据他们输入的内容进行输出。 the tutorial hard codes the values and i can get that to work but i am trying to go to the next step and get them to input values and use them.
本教程对值进行了硬编码,我可以使其正常工作,但是我正尝试进入下一步,让它们输入值并使用它们。 so far all the code does is let them enter values put does not post them to the output.
到目前为止,所有代码所做的只是让它们输入值,而没有将其发布到输出中。 below is both sets of code
以下是两组代码
here is the code from the tutorial i am using: (can be found here: http://www.tutorialspoint.com/python/python_classes_objects.htm
) 这是我正在使用的教程中的代码:(可以在这里找到:
http://www.tutorialspoint.com/python/python_classes_objects.htm
: 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
here is my code 这是我的代码
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()
You're doing this at the wrong place. 您在错误的位置执行此操作。 You need to do this outside the class, at the point where you're instantiating them:
您需要在类之外,实例化它们时执行此操作:
personName = raw_input('Enter your name: ')
personAge = raw_input('Enter your age: ')
person1 = People(personName, personAge)
person1.displayPerson()
Note that since this appears to be Python 2.7, you should use raw_input
instead of input
. 请注意,由于这似乎是Python 2.7,因此应使用
raw_input
而不是input
。 Also you should inherit your class from object
. 同样,您应该从
object
继承您的类。
You should move the input code out of the class statement,like this. 您应该这样将输入代码移出class语句。
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.