我知道这可能是一个简单的问题,但在查看了python 2.6.4的文档后,我似乎无法找出问题所在。这是我的文件,完整的。我遇到的问题是在get_phone_number()中。在询问了电话号码后,我收到了这个错误:
Traceback (most recent call last):
File "/home/charles/workspace/HelloWorld/hello.py", line 27, in <module>
c.get_phone_number()
File "/home/charles/workspace/HelloWorld/hello.py", line 17, in get_phone_number
self.phone_number[phone_count]
AttributeError: Contact instance has no attribute 'phone_number'
似乎我能够动态定义属性,但如果它是列表则不能?请帮忙!
class Name():
def get_name(self):
self.first = raw_input("First Name?\n")
self.middle = raw_input("Middle Name?\n")
self.last = raw_input("Last Name?\n")
pass
class Address():
def get_address(self):
self.street = raw_input("Street?\n")
self.city = raw_input("City?\n")
self.zip = raw_input("Zip Code?\n")
pass
class Phone_Number():
def get_phone_number(self):
count = 0
phone_count = raw_input("How many phone numbers?\n")
self.phone_number[phone_count]
while count < (phone_count - 1):
self.phone_number[phone_count] = raw_input("Phone Number: ")
phone_count -= 1
pass
class Contact(Name, Address, Phone_Number):
pass
c = Contact()
c.get_name()
c.get_address()
c.get_phone_number()
答案 0 :(得分:2)
替换
self.phone_number[phone_count]
与
self.phone_number = []
第一个语句什么都不做(实际上,它试图访问self中名为phone_number的列表的phone_count-th元素,这个元素不存在,因而错误)。
第二个语句定义了一个名为phone_number的新列表。
答案 1 :(得分:1)
您的代码包含很多错误,而不是Pythonic。一些要点:您需要将第一个用户输入转换为整数。您可以使用for循环而不是while循环。在Python 2.5上,您可以使用xrange而不是range,但是对于Python 3.0使用范围。使用append将项添加到列表中。
class Phone_Number():
def get_phone_numbers(self):
phone_count = int(raw_input("How many phone numbers?\n"))
self.phone_numbers = []
for _ in range(phone_count):
self.phone_numbers.append(raw_input("Phone Number: "))
p = Phone_Number()
p.get_phone_numbers()
for phone_number in p.phone_numbers:
print phone_number
答案 2 :(得分:0)
您需要初始化self.phone_number
def get_phone_number(self):
count = 0
phone_count = raw_input("How many phone numbers?\n")
self.phone_number = []
while count < (phone_count - 1):
self.phone_number.append (raw_input("Phone Number: "))
phone_count -= 1