为什么我无法正确访问课程列表?

问题描述 投票:-1回答:3

我是Python的新手。我正在制作可以访问课程的基本列表。但是,当我将其发送到输出时,终端将其列为基本对象,而不是单独列出每个类项目。这是代码:

     # Make a class with attributes
    class Persons(object):
         def __init__(self, firstName=None, lastName=None):
            self.firstName = firstName
            self.lastName = lastName

    # Make list with said attributes
        def newList():
            nameList = []
            nameList.append(Persons("Mathew", "Dodson"))
            nameList.append(Persons("Dr", "Kin"))

    # Print out said list

           print(str(nameList.firstName))
           print(str(nameList.lastName))

     newList()

我很确定我的语法完全错误。如果有人可以帮助,将不胜感激。

python
3个回答
1
投票

nameList是一个列表-它包含Person个对象。 nameList.firstname将不起作用。您将需要在nameList中选择这些Person之一,然后访问属性。例如:

# Print out said list

print(str(nameList[0].firstName)) # Mathew
print(str(nameList[1].lastName))  # Kin

如果要打印整个列表:

for person in nameList:
    print(person.firstName)
    print(person.lastName)

2
投票

列出清单

要创建列表,您不需要进行连续的追加,只需像这样一口气声明它:

name_list = [Persons('Mathew', 'Dodson'), Persons('Dr', 'Kin')]

迭代列表

列表本身没有first_name属性。但是元素可以。

for person in name_list:
    print(person.first_name)
    print(person.last_name)

很抱歉更改您的命名约定,但是每个人都在python中使用蛇形大小写。您可以在PEP8中进一步探索。


0
投票

[nameListlistlist不具有firstNamelastName属性(list自动访问其成员的属性没有魔术。]

类似地,您说“终端将其列为基本对象,而不是分别列出每个类项目。”这是因为与list一样,对象的repr也没有提供足够的信息,但是与list不同,您可以自定义它。

如果目标是打印出每个人的名字和姓氏,则可以执行以下操作:

 for person in nameList:
     print(person.firstName, person.lastName)  # Separates with a space

您还可以通过为您的类定义__str____repr__来实现,这样会自动生成更有用的字符串形式,例如:

class Persons(object):
    def __init__(self, firstName=None, lastName=None):
        self.firstName = firstName
        self.lastName = lastName
    def __repr__(self):
        return 'Persons({!r}, {!r})'.format(self.firstName, self.lastName)
    def __str__(self):
        return '{} {}'.format(self.firstName, self.lastName)

这将使您获得与我刚才描述的第一个循环相同的结果:

 for person in nameList:
     print(person)  # __str__ is called automatically, and you made it return something useful
© www.soinside.com 2019 - 2024. All rights reserved.