class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
如何要求用户输入姓名和年龄?
答案 0 :(得分:2)
您可以在init中进行。如果在Python 2.7中,请使用raw_input
class Person:
def __init__(self):
self.name = input('Name: ')
self.age = int(input('Age: ')
p1 = Person()
print(p1.name)
print(p1.age)
或者如果您想将其保留在外面
class Person:
def __init__(self,name,age):
self.name = name
self.age = age
name = input('Name: ')
age = int(input('Age: '))
p1 = Person(name,age)
print(p1.name)
print(p1.age)
答案 1 :(得分:0)
This会有所帮助,但简单的答案是:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person((raw_input("Enter Name"), int(raw_input("Enter Age"))))
print(p1.name)
print(p1.age)
答案 2 :(得分:0)
The input
function来获取用户的输入。您可以根据以下用户输入创建新的Person
:
p1 = Person(input("What is your name?"), int(input("What is your age?")))
这是一种防止非整数用户输入年龄时输入的方法:
name = input("What is your name?")
try:
age = int(input("What is your age?"))
except:
print("Invalid input.")
exit()
p1 = Person(name, age)
答案 3 :(得分:0)
您可以将input()
用于Python 3:
name = input('Enter your name:')
age = input('Enter your age: ')
和raw_input()
用于Python 2:
name = raw_input('Enter your name:')
age = raw_input('Enter your age: ')
请注意,在读取用户输入时,您需要将age
强制转换为int
,因为您将获得字符串值。
age = int(age)
但是请注意,如果用户给出无效的int
,则会抛出错误