Python 初学者 - <bound method ... of <... object at 0x00000000005EAAEB8>>从? [英] Python Beginner - where comes <bound method ... of <... object at 0x0000000005EAAEB8>> from?

查看:207
本文介绍了Python 初学者 - <bound method ... of <... object at 0x00000000005EAAEB8>>从?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有课

class ActivationResult(object):

    def __init__(self, successful : bool):
        self._successful = successful

    def getSuccessful(self) -> bool:
        return self._successful

还有一个测试

def testSuccessfulFromCreate(self):

    target = ActivationResult(True)

    self.assertEquals(target._successful, True)
    self.assertEquals(target.getSuccessful, True)

第一个断言是好的,但第二个断言失败了 AssertionError: <bound method ActivationResult.getSuccess[84 chars]EB8>>!= 真

The first assert is good, but the second one fails with AssertionError: <bound method ActivationResult.getSuccess[84 chars]EB8>> != True

当我尝试打印时,也会发生同样的事情.为什么?

The same thing happens, when I try to print it. Why?

推荐答案

你得到的是方法,而不是调用它.
试试:

You are getting the method, not calling it.
Try :

self.assertEquals(target.getSuccessful(), True)  # With parenthesss

第一次就可以了,因为您获得了属性 _successful,该属性已使用 True 正确初始化.
但是当你调用target.getSuccessful时,它你的方法对象本身,你似乎想要调用强>那个方法.

It's OK the first time because you get the attribute _successful, which was correctly initialized with True.
But when you call target.getSuccessful it gives you the method object itself, where it seems like you want to actuall call that method.

说明

以下是打印对象方法时发生的相同事情的示例:

Here is an example of the same thing that happens when you print an object's method:

class Something(object):
    def somefunction(arg1, arg2=False):
        print("Hello SO!")
        return 42

我们有一个类,有一个方法.
现在,如果我们打印它,但不调用它:

We have a class, with a method.
Now if we print it, but not calling it :

s = Something()
print(s.somefunction)  # NO parentheses
>>> <bound method Something.somefunction of <__main__.Something object at 0x7fd27bb19110>>

我们得到与您的问题相同的输出 .这就是方法在打印时的表示方式.

We get the same output <bound method ... at 0x...> as in your issue. This is just how the method is represented when printed itself.

现在,如果我们打印它并实际调用它:

Now if we print it and actually call it:

s = Something()
print(s.somefunction())  # WITH parentheses
>>>Hello SO!
>>>42

方法被调用(它打印Hello SO!),并且它的返回也被打印出来(42)

The method is called (it prints Hello SO!), and its return is printed too (42)

这篇关于Python 初学者 - &lt;bound method ... of &lt;... object at 0x00000000005EAAEB8&gt;&gt;从?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆