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
351 views
in Technique[技术] by (71.8m points)

python - 获取实例的类名?(Getting the class name of an instance?)

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 has been derived?

(如果我从中执行此操作的函数是实例的类派生的基类,如何找出在Python中创建对象实例的类的名称?)

Was thinking maybe the inspect module might have helped me out here, but it doesn't seem to give me what I want.

(想到也许检查模块可能在这里帮助了我,但它似乎没有给我我想要的东西。)

And short of parsing the __class__ member, I'm not sure how to get at this information.

(如果没有解析__class__成员,我不知道如何获取这些信息。)

  ask by Dan translate from so

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

1 Answer

0 votes
by (71.8m points)

Have you tried the __name__ attribute of the class?

(您是否尝试过__name__属性?)

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

(即type(x).__name__将为您提供类的名称,我认为这就是您想要的。)

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

This method works with new-style classes only.

(此方法仅适用于新样式的类 。)

Your code might use some old-style classes.

(您的代码可能会使用一些旧式类。)

The following works for both:

(以下适用于:)

x.__class__.__name__

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

...