繁体   English   中英

遍历列表中的元素时,如何在 python 中创建对象?

[英]How do I create objects in python when iterating through elements in a list?

我试图将列表中的元素传递给一个类以在 Python 中创建一个对象。 后来,当我使用相同的列表尝试回忆该对象时,我收到错误消息:'str' 对象没有属性 'name'。

我已经使用 Python 一段时间了,但对 OOP 还是陌生的。 想知道这是否与对象的范围有关>

class SwimmingWithTheFishes:
    def __init__(self, typeofshark):
        self.name = typeofshark

    def __str__(self):
        return f"This is the method shark: {self.name}"

    def reporting(self, shark):
        name = shark.name
        print(f"This is a method shark: {name}")

    def print_return(self):
        return f'{self.name}'


def main():
    # sharklist = [{"name": "mako"}, {"name": "hammerhead"}, {"name": "greatwhite"}, {"name": "reef"}]
    sharklist = ["mako", "hammerhead", "greatwhite", "reef"]

    for typeofshark in sharklist:
        typeofshark = SwimmingWithTheFishes(typeofshark)
        print(f"Heavens above, that's no fish: {typeofshark.name}")
        typeofshark.reporting(typeofshark)

    for shark in sharklist:
        print(SwimmingWithTheFishes.print_return(shark))


if __name__ == "__main__":
    main() 

当您迭代列表并分配给当前变量时,您不会更改列表中的值,您只会更改该局部变量。

例如

>>> l = [1,2,3]
>>> for i in l:
...     i += 1
... 
>>> l
[1, 2, 3]

要修改列表,您应该创建一个新列表,因为如果修改您迭代的列表,您可能会遇到问题。 这个新列表可以被称为类似sharks东西——其中的元素包含类实例。

最后,你对方法也有一个误解……你不需要每次在实例上调用方法时都传入对象的引用。 方法函数的self参数自动采用您从中调用方法的实例的值。

这使得最终代码:

class SwimmingWithTheFishes:
    def __init__(self, typeofshark):
        self.name = typeofshark

    def __str__(self):
        return f"I am a {self.name} shark."

    def reporting(self):
        print(f"This is a {self.name} shark method.") 


def main():
    # shark_types = [{"name": "mako"}, {"name": "hammerhead"}, {"name": "greatwhite"}, {"name": "reef"}]
    shark_types = ["mako", "hammerhead", "greatwhite", "reef"]
    sharks = []

    for type_ in shark_types:
        shark = SwimmingWithTheFishes(type_)
        sharks.append(shark)
        print(f"Heavens above, that's no fish: {shark.name}")
        shark.reporting()

    for shark in sharks:
        print(shark)


if __name__ == "__main__":
    main() 

这使:

Heavens above, that's no fish: mako
This is a mako shark method.
Heavens above, that's no fish: hammerhead
This is a hammerhead shark method.
Heavens above, that's no fish: greatwhite
This is a greatwhite shark method.
Heavens above, that's no fish: reef
This is a reef shark method.
I am a mako shark.
I am a hammerhead shark.
I am a greatwhite shark.
I am a reef shark.

print_returnSwimmingWithTheFishes一个方法,所以你应该用shark实例化SwimmingWithTheFishes ,这样self就会成为SwimmingWithTheFishes的对象,让self.nameprint_return工作。

改变:

print(SwimmingWithTheFishes.print_return(shark))

到:

print(SwimmingWithTheFishes(shark).print_return())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM