【问题标题】:Self in Class Demanding Argument课堂上的自我要求的论点
【发布时间】:2011-12-10 12:57:16
【问题描述】:

由于某种原因,大多数类实例都返回类型错误,说明传递的参数不足,问题出在 self. 这工作正常:

class ExampleClass:
    def __init__(self, some_message):
        self.message = some_message
        print ("New ExampleClass instance created, with message:")
        print (self.message)
ex = ExampleClass("message")

但是,我定义和调用实例的几乎所有其他类都返回相同的错误。几乎相同的功能:

class Test(object):
    def __init__(self):
        self.defaultmsg = "message"
    def say(self):
        print(self.defaultmsg)
test = Test
test.say()

返回一个类型错误,表示它需要一个参数。我不仅在那个类中遇到了这个问题,而且在我定义的几乎每个类中都遇到了这个问题,我不知道问题是什么。我刚刚更新了python,但之前遇到了错误。我对编程还很陌生。

【问题讨论】:

    标签: python class python-3.x self typeerror


    【解决方案1】:

    你必须实例化这个类:

    test = Test()   #test is an instance of class Test
    

    而不是

    test = Test     #test is the class Test
    test.say()      #TypeError: unbound method say() must be called with Test instance as first argum ent (got nothing instead)
    

    如果你好奇,可以试试这个:

    test = Test
    test.say(Test())     #same as Test.say(Test()) 
    

    之所以有效,是因为我将类实例(self)赋予了未绑定的方法!
    绝对不建议以这种方式编码。

    【讨论】:

    • 我的第一个想法:test = Test; test.say(test())
    【解决方案2】:

    你应该添加括号来实例化一个类:

    test = Test()
    

    【讨论】:

      【解决方案3】:

      您的测试指的是类本身,而不是该类的实例。要创建一个实际的测试实例,或“实例化”它,请添加括号。例如:

      >>> class Foo(object):
      ...   pass
      ... 
      >>> Foo
      <class '__main__.Foo'>
      >>> Foo()
      <__main__.Foo object at 0xa2eb50>
      

      错误消息试图告诉您没有这样的 self 对象可以(隐式)作为函数参数传入,因为在您的情况下,test.say 将是一个未绑定的方法。

      【讨论】:

        猜你喜欢
        • 2016-08-02
        • 2012-01-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多