1

Suppose I have this class:

class Foo(): def foo_method(self): pass 

Now suppose I have an object foo = Foo(). I can pass foo.foo_method around as argument to a function. foo.foo_method.__qualname__ returns the string representing the method's "full name": "Foo.foo_method". What if I want to get Foo, the class itself, from foo.foo_method?

The solution I came up with is:

def method_class(method): return eval(method.__qualname__.split(".")[0]) 

Is there a less "dirty" way of achieving this?

2
  • 3
    maybe dir(foo) or help(foo) print either of those and try Commented Apr 13, 2021 at 20:00
  • 1
    Have you looked at __self__ of foo_method? Commented Apr 13, 2021 at 20:07

2 Answers 2

3

The instance that a bound method is bound to, is stored as the __self__ attribute. Thus:

class Foo: def foo_method(self): pass foo = Foo() assert foo.foo_method.__self__.__class__ is Foo 
Sign up to request clarification or add additional context in comments.

Comments

1

The following might do what you want:

 ########################################################## class Klassy: def methy(arg): pass insty = Klassy() funky = insty.methy ########################################################## insty_jr = funky.__self__ Klassy_jr = type(insty_jr) print(Klassy_jr) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.