Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

mocking

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?

like image 249
user1454693 Avatar asked Aug 01 '12 23:08

user1454693


1 Answers

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.

like image 163
Andrew Clark Avatar answered Nov 04 '22 18:11

Andrew Clark