Daniel Diniz
Daniel Diniz

Reputation: 174

Given a Python method, how to get its class?

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?

Upvotes: 1

Views: 64

Answers (2)

Toothpick Anemone
Toothpick Anemone

Reputation: 4644

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)

Upvotes: 1

Karl Knechtel
Karl Knechtel

Reputation: 61519

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

Upvotes: 3

Related Questions