[英]How am I able to fix an attribute error when using classes
编写一个名为“Person”的 class,其中包含人名、地址和电话号码的数据属性。
class Person:
def __init__(self, n, a, p):
self.name = n
self.address = a
self.phone = p
def set_name(self, n):
self.name = n
def set_address(self, a):
self.address = a
def set_phone(self, p):
self.phone = p
def get_name(self):
return 'Customer Name:'
def get_address(self):
return 'Customer Address:'
def get_phone(self):
return 'Customer Phone Number:'
def main():
n = input('Enter Customer Name: ')
a = input('Enter the Customer Address: ')
p = input('Enter the Customer Phone Number: ')
print(n.get_person())
print(a.get_address())
print(p.get_phone())
main()
如何修复我的属性错误?
首先,您的错误确实应该是TypeError
,因为您正在从 class 调用实例方法:
>>> class Foo:
... def __init__(self):
... self.bar = 1
... def thing(self):
... return self.bar
...
>>>
>>>
>>> Foo.thing()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: thing() missing 1 required positional argument: 'self'
但是,无论如何修复都是相同的。
您需要创建一个 class 的实例来访问其属性:
class Foo:
def __init__(self):
self.bar = 1
# Foo is a class, but it doesn't have a
# bar attribute. An *instance* of the class
# does
# this raises an attributeError
Foo.bar
AttributeError
# this doesn't, because we created an instance
foo = Foo()
foo.bar
1
您需要创建一个 person 实例,然后您可以获取它的属性:
class Person:
def __init__(self, name, address, phone):
self.name = name
self.address = address
self.phone = phone
Person.phone
# AttributeError
# Create an instance of Person here
tim = Person(name='Tim', address='1234 Main St', phone='555-5555')
# Then you can get Tim's information
tim.phone
'555-5555'
您需要使用person = Person(n, a, p)
之类的东西创建 Person class 的实例。 在main()
function 的输入语句之后执行此操作。
其次,在打印出属性时,您需要引用您创建的 Person class 的实例(即 person.get_person()、person.get_address() 等)。
最后,在调用 get function 时,请确保这些函数返回您要查找的值。 function get_address()
应该返回 self.address。
这是我的建议:
class Person:
def __init__(self, n, a, p):
self.name = n
self.address = a
self.phone = p
def set_name(self, n):
self.name = n
def set_address(self, a):
self.address = a
def set_phone(self, p):
self.phone = p
def get_name(self):
return self.name
def get_address(self):
return self.address
def get_phone(self):
return self.phone
def main():
n = input('Enter Customer Name: ')
a = input('Enter the Customer Address: ')
p = input('Enter the Customer Phone Number: ')
person = Person(n, a, p) # create the instance
# get attributes of instantiated object
print(person.get_person())
print(person.get_address())
print(person.get_phone())
main()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.