I want to check (in my tests) that a method of object is the same as a method of a given class.
class Cls:
def foo(self):
pass
obj = Cls()
assert obj.foo == Cls.foo # assert will fail
Which operation can be used instead of obj.foo == Cls.foo
to produce True
if the bound method is the same as unbound (except for 'boundness')?
On Python 2.7.x :
>>> Cls.foo.__func__ is obj.foo.__func__
True
In Python 3:
>>> class Cls:
... def foo(self):
... pass
...
>>> obj = Cls()
>>> obj.foo
<bound method Cls.foo of <__main__.Cls object at 0x101d8f588>>
>>> dir(obj.foo)
['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__func__', '__ge__', '__get__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
>>> obj.foo.__func__
<function Cls.foo at 0x101d92400>
>>> obj.foo.__func__ is Cls.foo
True
Looking through the dir()
of an object is an easy way to explore and look for potentially useful attributes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With