简体   繁体   中英

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

要获取类名的字符串表示,我们可以使用obj.__class__.__name__是否可以重载这些方法,以便我可以返回我的字符串而不是实际的类名?

Yep.

class A:
    def __init__(self):
        self.__class__.__name__ = 'B'

But this seems like a bad idea.

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.

You can do this:

>>> class Foo(object):
...     def __init__(self):
...             self.__class__.__name__ = "Bar"
... 
>>> print Foo().__class__.__name__
Bar

Or you can make your own double underscore attribute.

>>> class Foo(object):
...     __name__ = "Bar"
... 
>>> print Foo().__name__
Bar

But why would you want to do this? I don't see any possible use for this. BTW, I realize this is not the same as __class__.__name__ , but I don't think changing __class__.__name__ is generally a good idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM