Python 实例没有 __call__ 方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2310432/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-04 00:20:34  来源:igfitidea点击:

Python instance has no __call__ method

pythonclassinstance

提问by tyblu

I've been learning how to use Python for the better part of today after giving up on an ugly bash script.

在放弃丑陋的 bash 脚本后,我一直在学习如何在今天的大部分时间里使用 Python。

I'm trying to use 2 classes to define a few arrays of objects in which to store some unique strings and integers (1-10). The objects will consist of the following:

我正在尝试使用 2 个类来定义一些对象数组,以在其中存储一些唯一的字符串和整数 (1-10)。这些对象将包括以下内容:

object[i].user
         .n     # n = i
         .name
         .coords
         .hero

(param1, param2, param3) will be different for each object.n and object.user, so I'm trying to use an assignment method that doesn't look like garbage after writing 90 unique strings. Nesting an example I found didn't work, so here's the compromise:

(param1, param2, param3) 对于每个 object.n 和 object.user 都会不同,所以我尝试使用一种在写入 90 个唯一字符串后看起来不像垃圾的赋值方法。嵌套一个我发现的例子不起作用,所以这是妥协:

class CityBean:
    def __init__(self,name,coords,hero):
        self.name = name
        self.coords = coords
        self.hero = hero

class Castles:
    def __init__(self,user,n):
        self.user = user
        self.n = n
        if self.user == 'user1':
            temp = {
                1:  CityBean( "name1"  , "coord1" , "hero1"),
                ... blah blah blah
                10: CityBean( "name10" , "coord10" , "hero10" )}[self.n]()
        if self.user == 'user2':
            temp = {
                1:  CityBean( "name11" , "coord11" , "hero11" ),
                ... blah blah blah
                10: CityBean( "name20" , "coord20" , "hero20" ) }[self.n]()
        if self.user == 'user3':
            temp = {
                1:  CityBean( "name21" , "coord21" , "hero21" ),
                ... blah blah blah
                10: CityBean( "name30" , "coord30" , "hero30" ) }[self.n]()
        self.name = temp.name
        self.coords = temp.coords
        self.hero = temp.coords
        __del__(temp)

I call it with something like this:

我这样称呼它:

cities = list( Castles("user2",i) for i in range(1,11) )

It gives me this error:

它给了我这个错误:

AttributeError: CityBean instance has no __call__ method

And it blames this line:

它归咎于这一行:

                10: CityBean( "name20" , "coord20" , "hero20" ) }[self.n]() # pseudo
                10: CityBean( "" , "" , "" ) }[self.n]() # what is actually looks like

What's wrong with my cruddy classes? I'm doing something retarded, aren't I?

我粗糙的课程有什么问题?我正在做一些迟钝的事情,不是吗?

回答by nosklo

It's really hard to guess what you want from what you provided, since, instead of saying what you want to do, you provided your newbie code, so one has a hard guess time.

很难从您提供的内容中猜测您想要什么,因为您提供了新手代码,而不是说出您想要做什么,因此很难猜测时间。

I'd think something like this would do:

我认为这样的事情会做:

data = {
        (1, 'user1'): ("name1", "coord1", "hero1"),
        (2, 'user1'): ("name2", "coord2", "hero2"),
        #...
        (1, 'user2'): ("name11", "coord11", "hero11"),
        (2, 'user2'): ("name12", "coord12", "hero12"),
        # ...
    }


class CityBean:
    def __init__(self,name,coords,hero):
        self.name = name
        self.coords = coords
        self.hero = hero

class Castles:
    def __init__(self,user,n):
        self.user = user
        self.n = n
        name, coords, hero = data.get((n, user))
        self.citybean = CityBean(name, coords, hero)

回答by S.Lott

Why did your write this?

你为什么写这个?

temp = {
            1:  CityBean( "name21" , "coord21" , "hero21" ),
            ... blah blah blah
            10: CityBean( "name30" , "coord30" , "hero30" ) }[self.n]()

What do you think temp= {...}[something]()will do?

你认为temp= {...}[something]()会做什么?

  1. It creates a dictionary. {...}

  2. It picks one item out of the dictionary. {...}[something]. This will be a CityBeanobject.

  3. It evaluates that one item as a function {...}[something]()Is CityBean(...)()

  1. 它创建了一个字典。 {...}

  2. 它从字典中挑选一项。 {...}[something]. 这将是一个CityBean对象。

  3. 它评估一个项目作为一个函数{...}[something]()CityBean(...)()

Why are you calling the CityBean object as if it was a function?

为什么要像调用函数一样调用 CityBean 对象?

Further, why are you creating entire dictionaries only to pick a single item of it? What's wrong with ifstatements?

此外,你为什么要创建整个字典只是为了选择其中的一个项目?if陈述有什么问题?

回答by Anurag Uniyal

your are doing

你在做什么

{
1:  CityBean( "name1"  , "coord1" , "hero1"),
... blah blah blah
10: CityBean( "name10" , "coord10" , "hero10" )}[self.n]()

which is basically from a dict get value based on key, values on your dict are CityBean instances, so in short you are doing this

这基本上是从基于键的 dict 获取值,你的 dict 上的值是 CityBean 实例,所以简而言之,你正在这样做

CityBean( "name1"  , "coord1" , "hero1")()

which is valid but will call the special method __call__of the instance, so either remove ()or add a __call__method depending on the need

这是有效的,但会调用__call__实例的特殊方法,因此根据需要删除()或添加__call__方法

回答by extraneon

I don't really understand what you're trying to do exactly, but:

我真的不明白你到底想做什么,但是:

 10: CityBean( "name10" , "coord10" , "hero10" )}[self.n]()

if calling something (the () at the end make it a function call).

如果调用某些内容(最后的 () 使其成为函数调用)。

What you would want is I think temp = { ... 10: CityBean( "name10" , "coord10" , "hero10" )}[self.n]

你想要的是我认为 temp = { ... 10: CityBean( "name10" , "coord10" , "hero10" )}[self.n]

In that case you'd get the dict entry with key n and label that temp.

在这种情况下,您将获得带有键 n 的 dict 条目并标记该温度。

回答by Thomas Ahle

Notice, that in python, when you write

注意,在 python 中,当你写

CityBean( "name1"  , "coord1" , "hero1")

You initialize the object CityBean. There is no need for an extra ().

您初始化对象CityBean。不需要额外的().

回答by Kemin Zhou

You can get this problem if you do something wrong

如果你做错了什么,你会遇到这个问题

os.environ("METAG_DATA")

The correct way is

正确的方法是

os.environ["METAG_DATA"]

回答by Ignacio Vazquez-Abrams

Putting parens after a class name in a normal expression instantiates it immediately. If you want to delay instantiation then you'll need to use lambdaor functools.partial():

将括号放在普通表达式中的类名之后会立即实例化它。如果要延迟实例化,则需要使用lambdafunctools.partial()

10: lambda: CityBean("", "", "")}...