1

我正在使用@classobj. 我不仅在设置变量,还在新类中调用方法:

class Example:
    def __init__(self):
        pass

    @classmethod
    def constructor1(cls,x,y):
        self=cls
        self.__x = x
        self.__somemethod(self,y)

    ...

我收到以下错误:

unbound method __somemethod() must be called with Example instance as 
first argument (got classobj instance instead)

我该如何解决这个问题?

4

4 回答 4

3

如果您希望您的类方法成为构造函数,您可能希望创建一个以cls. 我怀疑你正试图用你的self = cls行来做到这一点,但你实际上并没有创建一个新实例,因为你忽略了括号。还有一些其他问题,但我认为这是关键问题。这是一个固定的构造函数:

@classmethod
def constructor1(cls,x,y):
    self=cls()                # parentheses added, to make it a call
    self.__x = x
    self.__somemethod(y)      # self is not needed as a parameter here
    return self               # return the new instance
于 2012-09-29T10:42:32.203 回答
2

看起来__somemethod不是类方法,而是“普通”方法。普通方法期望一个实际的实例作为第一个参数,而不是一个类。因为constructor1被装饰为@classmethod,cls是类本身 - 你传递给__somemethod. 那是行不通的。

你应该重新考虑你的设计方法。

附录:

也许你的意思是这样的?

@classmethod
def constructor1(cls, x, y):
    newinst = cls()
    newinst.__x = x
    cls.__somemethod(newinst, y)

不过,最好按如下方式编写:

@classmethod
def constructor1(cls, x, y):
    newinst = cls()
    newinst.__x = x
    newinst.__somemethod(y)

实际上,我喜欢较近的方法——对我来说似乎是一种过于复杂的代名词。

于 2012-09-29T10:30:01.473 回答
1

这可能是我认为你正在努力实现的模板......

import random

class Something(object):
    def __init__(self, value, **kwargs):
        self.value = value
        for k, v in kwargs.iteritems():
            setattr(self, k, v)
    @classmethod
    def from_iterable(cls, iterable):
        return cls(sum(iterable), description='came from from_iterable')
    @classmethod
    def make_random(cls):
        return cls(random.randint(1,1000), is_random=True)

a = Something.from_iterable([1, 2, 3])
b = Something.make_random()
c = Something(56)

for obj in (a, b, c):
    print type(obj), obj.value

<class '__main__.Something'> 6
<class '__main__.Something'> 308
<class '__main__.Something'> 56
于 2012-09-29T10:41:00.430 回答
1

感谢 ch3ka 的回答和 Tim Pietzcker 的评论,我发现了我的错误:我使用了来自http://jjinux.blogspot.co.at/2008/11/python-class-methods-make-good.html的工厂方法并忘记了()在行self=cls()。现在它工作得很好:

class Example:
    def __init__(self):
        pass

    @classmethod
    def constructor1(cls,x,y):
        self=cls()
        self.__x = x
        self.__somemethod(self,y)

    ...
于 2012-09-29T10:41:20.807 回答