我是Python的新手,我只是在学习Classes,并且正在尝试编写“个人信息”程序:
这是我的代码:
class PersonalInfo():
def names(self, name):
name = raw_input("What is your name?")
self.names = name
def addresses(self, add):
add = raw_input("What is your adress?")
self.addresses = add
def ages(self, age):
age = raw_input("What is your age?")
self.ages = age
def numbers(self, number):
number = raw_input("What is your phone number?")
self.numbers = number
PersonalInfo()
def print_names():
info = PersonalInfo()
print "Name:", info.names(name)
print "Address:", info.addresses(add)
print "Age:", info.info.ages(age)
print "Phone number:", info.numbers(number)
print_names()
但是当我运行它时会说:
NameError: global name 'add' is not defined
有人可以帮帮我吗?
答案 0 :(得分:4)
除NameError
之外,您的代码存在一些问题,我强烈建议您阅读有关python类的更多信息:
https://docs.python.org/2/tutorial/classes.html
https://www.tutorialspoint.com/python/python_classes_objects.htm
https://en.wikibooks.org/wiki/A_Beginner“s_Python_Tutorial /类
我会告诉你这些问题。
首先,NameError
发生是因为未定义add
变量。这同样适用于您在print语句中提供的所有其他参数。
其次,定义类方法的方式存在问题:
class PersonalInfo():
def names(self, name):
name = raw_input("What is your name?")
self.names = name
在这里,您将name
变量重新分配给raw_input
的返回值,因此首先将其设置为参数是没有意义的。另外,通过声明self.names = name
,您正在将类方法重新分配给raw_input
返回的字符串!
第三,您必须在调用方法或使用raw_input
时决定是否要提供信息。这是一个代码的工作示例,假设您要使用raw_input
class PersonalInfo():
def names(self):
name = raw_input("What is your name?")
self.name = name
def addresses(self):
add = raw_input("What is your adress?")
self.address = add
def ages(self):
age = raw_input("What is your age?")
self.age = age
def numbers(self):
number = raw_input("What is your phone number?")
self.number = number
def print_names():
info = PersonalInfo()
# Get information
info.names()
info.addresses()
info.ages()
info.numbers()
# After getting the info, print it
print "Name:", info.name
print "Address:", info.address
print "Age:", info.age
print "Phone number:", info.number
print_names()