I'm wondering how to convert a python 'type' object into a string using python's reflective capabilities.
For example, I'd like to print the type of an object
print "My type is " + type(someObject) # (which obviously doesn't work like this)
We can convert Object to String in java using toString() method of Object class or String. valueOf(object) method. You can convert any object to String in java whether it is user-defined class, StringBuilder, StringBuffer or anything else.
The best way to checks if the object is a string is by using the isinstance() method in Python. This function returns True if the given object is an instance of class classified or any subclass of class info, otherwise returns False.
Converting Object to String Everything is an object in Python. So all the built-in objects can be converted to strings using the str() and repr() methods.
The global method String() can convert booleans to strings. The Boolean method toString() does the same.
print type(someObject).__name__
If that doesn't suit you, use this:
print some_instance.__class__.__name__
Example:
class A: pass print type(A()) # prints <type 'instance'> print A().__class__.__name__ # prints A
Also, it seems there are differences with type()
when using new-style classes vs old-style (that is, inheritance from object
). For a new-style class, type(someObject).__name__
returns the name, and for old-style classes it returns instance
.
>>> class A(object): pass >>> e = A() >>> e <__main__.A object at 0xb6d464ec> >>> print type(e) <class '__main__.A'> >>> print type(e).__name__ A >>>
what do you mean by convert into a string? you can define your own repr and str_ methods:
>>> 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
or i dont know..please add explainations ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With