pythonmocking

Is it possible to override `__name__` derived from object?


To get a string representation of a class name we can use obj.__class__.__name__ is it possible to overload these methods so that I can return my string instead of the actual class name?


Solution

  • Let's try! (Yes, this works):

    >>> class Foo(object):
    ...     pass
    ...
    >>> obj = Foo()
    >>> obj.__class__.__name__ = 'Bar'
    >>> obj
    <__main__.Bar object at 0x7fae8ba3af90>
    >>> obj.__class__
    <class '__main__.Bar'>
    

    You could also have just done Foo.__name__ = 'Bar', I used obj.__class__.__name__ to be consistent with your question.