'python get class name from object
I am trying to return a version number, with a way to implement exceptions.
Since the exceptions can be for any of my classes I am trying to get the classname from the object.
Problem is, I get a tuple instead of a string:
def version_control(*args):
version = 1.0
print args
#Exception example:
print str(args.__class__.__name__)
if 'User' == args.__class__.__name__:
version = 12.3
return version
How can I change the str(args.__class__.__name__) in such a way that it return the name of the class as string?
Solution 1:[1]
I get a tuple instead of a string
No, you get the string "tuple" instead of some other string, because args is a tuple of arguments.
When you call version_control(obj, 1, 2), args == (obj, 1, 2). You want to be looking at args[0], which in this example is obj
Solution 2:[2]
To get the class name as a string:
f = Foo()
f.__class__.__name__ # => 'Foo'
However, consider using isinstance() instead:
isinstance(f, Foo) # => True
This is more readable and covers a majority of use cases, and should be preferred when using a conditional.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Eric |
| Solution 2 |
