Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
673 views
in Technique[技术] by (71.8m points)

reflection - How to get (sub)class name from a static method in Python?

If I define:

class Bar(object):

    @staticmethod
    def bar():
        # code
        pass

class Foo(Bar):
    # code
    pass

Is it possible for a function call Foo.bar() to determine the class name Foo?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Replace the staticmethod with a classmethod. This will be passed the class when it is called, so you can get the class name from that.

class Bar(object):

    @classmethod
    def bar(cls):
        # code
        print cls.__name__

class Foo(Bar):
    # code
    pass

>>> Bar.bar()
Bar

>>> Foo.bar()
Foo

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...