gpt4 book ai didi

python - 尝试使用自定义类的 NameError

转载 作者:行者123 更新时间:2023-11-28 22:30:06 24 4
gpt4 key购买 nike

我是 Python 的新手,正在学习类,正在尝试编写一个“个人信息”程序:

这是我的代码:

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

有人可以帮帮我吗?

最佳答案

除了 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 变量。这同样适用于您在打印语句中提供的所有其他参数。

其次,您定义类方法的方式存在问题:

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()

关于python - 尝试使用自定义类的 NameError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42590506/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com