unbound method with instance as first argument got string but requires something else

和自甴很熟 提交于 2019-12-12 07:47:55

问题


#Maps.py
class Maps(object):

    def __init__(self):
        self.animals = []
        self.currently_occupied = {}

    def add_animal(self, name):
        self.animals.append(name)
        self.currently_occupied = {robot:[0, 0]}



#animal.py
class Animal(object):

    def __init__(self, name):
        import maps
        maps.add_animal(rbt)
        self.name = name


#Tproject.py
from Animal import Animal
Fred = Animal("Fred")

gives me this an error that looks like this

TypeError: unbound method add_animal() must be called with Maps instance as first argument (got str instance instead)

but i dont know what it means and i cannot figure it out searching through google or yahoo :(


回答1:


You need an instance of Maps, not the Maps class:

 maps.Maps.add_animal("Fred") # gives error

 mymap = maps.Map()

 mymap.add_animal("Fred") # should work

So you should either have a mymap attribute on the Animal class, per Animal instance or as a global object (whatever works best for your case).




回答2:


You're calling an unbound method, meaning you're accessing a method from a class itself, and not through an instance (so Python doesn't know which instance should be used as self). This code shouldn't give that error as shown, but I assume you're doing something like

maps.Maps.add_animal(rbt)

It's not clear what you're trying to do, or I'd offer a suggestion as to how to fix it.



来源:https://stackoverflow.com/questions/10645444/unbound-method-with-instance-as-first-argument-got-string-but-requires-something

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!