Getting the class name of an instance?

前端 未结 10 2297
情书的邮戳
情书的邮戳 2020-11-22 13:38

How do I find out a name of class that created an instance of an object in Python if the function I am doing this from is the base class of which the class of the instance h

10条回答
  •  鱼传尺愫
    2020-11-22 14:04

    class A:
      pass
    
    a = A()
    str(a.__class__)
    

    The sample code above (when input in the interactive interpreter) will produce '__main__.A' as opposed to 'A' which is produced if the __name__ attribute is invoked. By simply passing the result of A.__class__ to the str constructor the parsing is handled for you. However, you could also use the following code if you want something more explicit.

    "{0}.{1}".format(a.__class__.__module__,a.__class__.__name__)
    

    This behavior can be preferable if you have classes with the same name defined in separate modules.

    The sample code provided above was tested in Python 2.7.5.

提交回复
热议问题