Как определить класс python

Getting the class name of an instance

How do I find out the name of the class used to create an instance of an object in Python? I’m not sure if I should use the inspect module or parse the __class__ attribute.

12 Answers 12

Have you tried the __name__ attribute of the class? ie type(x).__name__ will give you the name of the class, which I think is what you want.

>>> import itertools >>> x = itertools.count(0) >>> type(x).__name__ 'count' 

If you’re still using Python 2, note that the above method works with new-style classes only (in Python 3+ all classes are «new-style» classes). Your code might use some old-style classes. The following works for both:

Why use __class__ over the type method? Like so: type(x).__name__ . Isn’t calling double underscore members directly discouraged? I can’t see a way around using __name__ , though.

You have to use __class__ directly to be compatible with old-style classes, since their type is just instance .

This is used often enough in logging, orm and framework code that there really should be a builtin typename(x) . requiring a user to look at the «guts» to get a name isn’t terribly pythonic, IMO.

Do you want the name of the class as a string?

instance.__class__.__name__ 

@EduardLuca why wouldn’t it be safe? Built-in properties use underscores so that they do not cause any conflict with the code you write

Well I know that single underscores mean / suggest that the method / property should be private (although you can’t really implement private methods in Python AFAIK), and I was wondering if that’s not the case with (some) double underscores too.

@EduardLuca Double underscores at the start only are similar to a single underscore at the start, but even more «private» (look up «python name mangling»). Double underscores at beginning and end are different — those are reserved for python and are not private (e.g. magic methods like __init__ and __add__).

>>> class A: . def whoami(self): . print(type(self).__name__) . >>> >>> class B(A): . pass . >>> >>> >>> o = B() >>> o.whoami() 'B' >>> 

or self.__class__.__name__ instead of type(self).__name__ to get the same behaviour. Unless there is something the type() function does that I am not aware of?

If you’re using type(item) on a list item the result will be while item.__class__.__name__ holds the class name.

I think the issue that @Grochni mentions is only relevant for certain classes in Python 2.x, see here: stackoverflow.com/questions/6666856/…

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.

".".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.

type(instance).__name__ != instance.__class__.__name__ # if class A is defined like class A(): . type(instance) == instance.__class__ # if class A is defined like class A(object): . 
>>> class aclass(object): . pass . >>> a = aclass() >>> type(a) >>> a.__class__ >>> >>> type(a).__name__ 'aclass' >>> >>> a.__class__.__name__ 'aclass' >>> >>> class bclass(): . pass . >>> b = bclass() >>> >>> type(b) >>> b.__class__ >>> type(b).__name__ 'instance' >>> >>> b.__class__.__name__ 'bclass' >>> 

This only holds true for old Python 2.x. In 3.x, bclass() would resolve to bclass(object). And even then, new classes appeared in Python 2.2.

Alternatively you can use the classmethod decorator:

class A: @classmethod def get_classname(cls): return cls.__name__ def use_classname(self): return self.get_classname() 
>>> A.get_classname() 'A' >>> a = A() >>> a.get_classname() 'A' >>> a.use_classname() 'A' 

Here’s a simple example based on GHZ’s which might help someone:

>>> class person(object): def init(self,name): self.name=name def info(self) print "My name is , I am a ".format(self.name,self.__class__.__name__) >>> bob = person(name='Robert') >>> bob.info() My name is Robert, I am a person 

Apart from grabbing the special __name__ attribute, you might find yourself in need of the qualified name for a given class/function. This is done by grabbing the types __qualname__ .

In most cases, these will be exactly the same, but, when dealing with nested classes/methods these differ in the output you get. For example:

class Spam: def meth(self): pass class Bar: pass >>> s = Spam() >>> type(s).__name__ 'Spam' >>> type(s).__qualname__ 'Spam' >>> type(s).Bar.__name__ # type not needed here 'Bar' >>> type(s).Bar.__qualname__ # type not needed here 'Spam.Bar' >>> type(s).meth.__name__ 'meth' >>> type(s).meth.__qualname__ 'Spam.meth' 

Since introspection is what you’re after, this is always you might want to consider.

Источник

Читайте также:  Python function object name
Оцените статью