Pythonの 'type'オブジェクトを文字列に変換します


152

Pythonの反射型機能を使用して、Pythonの「タイプ」オブジェクトを文字列に変換する方法を知りたいです。

たとえば、オブジェクトのタイプを印刷したい

print "My type is " + type(someObject) # (which obviously doesn't work like this)

1
オブジェクトの「タイプ」は何だと思いますか?そして、あなたが投稿したものについて何がうまくいかないのですか?
Falmarri、2011

謝罪、印刷タイプ(someObject)は実際に機能します:)
Rehno Lindeque '15

回答:


223
print type(someObject).__name__

それがあなたに合わない場合は、これを使用してください:

print some_instance.__class__.__name__

例:

class A:
    pass
print type(A())
# prints <type 'instance'>
print A().__class__.__name__
# prints A

また、type()新しいスタイルのクラスと古いスタイルのクラスを使用する場合(つまり、からの継承object)には違いがあるようです。新しいスタイルのクラスの場合type(someObject).__name__は名前を返し、古いスタイルのクラスの場合はを返しますinstance


3
実行print(type(someObject))すると完全な名前(パッケージを含む)が出力されます
MageWind '30

7
>>> class A(object): pass

>>> e = A()
>>> e
<__main__.A object at 0xb6d464ec>
>>> print type(e)
<class '__main__.A'>
>>> print type(e).__name__
A
>>> 

文字列に変換するとはどういう意味ですか?独自のreprおよびstr _メソッドを定義できます。

>>> class A(object):
    def __repr__(self):
        return 'hei, i am A or B or whatever'

>>> e = A()
>>> e
hei, i am A or B or whatever
>>> str(e)
hei, i am A or B or whatever

または私は知りません。説明を追加してください;)


ところで あなたの元の答えにはstr(type(someObject))も含まれていたと思います
レーノリンデケ11

4
print("My type is %s" % type(someObject)) # the type in python

または...

print("My type is %s" % type(someObject).__name__) # the object's type (the class you defined)


1

str()カスタムstrメソッドを使用する場合。これはreprでも機能します。

class TypeProxy:
    def __init__(self, _type):
        self._type = _type

    def __call__(self, *args, **kwargs):
        return self._type(*args, **kwargs)

    def __str__(self):
        return self._type.__name__

    def __repr__(self):
        return "TypeProxy(%s)" % (repr(self._type),)

>>> str(TypeProxy(str))
'str'
>>> str(TypeProxy(type("")))
'str'
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.