gpt4 book ai didi

python - 在迭代列表中的元素时,如何在 python 中创建对象?

转载 作者:行者123 更新时间:2023-12-01 09:01:03 24 4
gpt4 key购买 nike

我正在尝试将列表中的元素传递给类以在 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.

关于python - 在迭代列表中的元素时,如何在 python 中创建对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52455322/

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