python-3.x - 第二次调用相同的函数会导致类中的错误
问题描述
因此,由于某种原因,当我第一次调用函数时,它会创建请求数量的代理,但是当我第二次使用它时(在另一个函数中,time_skip 函数),这会给我一个错误。我已经坚持了一段时间,我似乎无法在任何地方找到答案。当代码通过 Create_agents 函数时会发生错误,但只有第二次。
class agent(object):
def __init__(self, identification, age):
self.identification = identification
self.age = age
def description(self):
print("My id is", self.identification)
print("My age is", self.age)
def Create_agents():
global id
list.append(agent(id,28 ))
id += 1
# functions
def Initialize():
for x in range(3):
Create_agents()
def Time_skip():
global year
year += 1
print("The new year is", year)
for agent in list:
agent.age +=1
Create_agents()
# Values
list = []
id = 0
year = 0
Initialize()
# Testing
for agent in list:
agent.description()
Time_skip()
for agent in list:
agent.description()
完整的输出是:
My id is 0
My age is 28
My id is 1
My age is 28
My id is 2
My age is 28
The new year is 1
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-76-4f7c476091fc> in <module>
37 agent.description()
38
---> 39 Time_skip()
40
41 for agent in list:
<ipython-input-76-4f7c476091fc> in Time_skip()
24 for agent in list:
25 agent.age +=1
---> 26 Create_agents()
27
28
<ipython-input-76-4f7c476091fc> in Create_agents()
10 def Create_agents():
11 global id
---> 12 list.append(agent(id,28 ))
13 id += 1
14
TypeError: 'agent' object is not callable
解决方案
The problem is you are overwriting the name of your class agent
in this for loop:
for agent in list:
agent.description()
Change your class name to Agent
and you will see the error is gone. This is why we should always follow some naming conventions, like mentioned in PEP8.
Edit:
I just realized that you are also overwriting the built-in function list
. This is what they call killing two birds with one stone **.
** I know it is overwritten earlier but whatever, it needs to be changed :)
推荐阅读
- python - 如何在不将整个文件加载到内存中的情况下更改大型(60gig)csv 文件的列名称?
- python-3.x - TypeError:“邮件”类型的参数不可迭代
- android - 无法引用 rust 为 android 应用程序制作的共享库的功能
- reactjs - 如何停止获取与 Redux 一起使用的用户媒体
- flutter - 使用gradle退出代码1颤动构建apk错误
- android - 可变实时数据值在创建片段时更新
- python - 如何在 Python PyAutoGUI 中更改键盘
- docker - 更改 nginx 配置文件
- javascript - 如何单击以将当前轮播幻灯片中的图像放置到画布上?
- php - 如何使用 str_replace 删除字符串中的一行中的 3 个斜杠