Вопрос

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?

Это было полезно?

Решение

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

Другие советы

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top