首页 > 解决方案 > 第二次调用相同的函数会导致类中的错误

问题描述

因此,由于某种原因,当我第一次调用函数时,它会创建请求数量的代理,但是当我第二次使用它时(在另一个函数中,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

标签: python-3.xclass

解决方案


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 :)


推荐阅读