推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
wcsjtu
V2EX  ›  Python

Python 怎么动态地给实例添加 magic method

  •  
  •   wcsjtu · May 14, 2018 · 2465 views
    This topic created in 2926 days ago, the information mentioned may be changed or developed.

    python2.7 怎么动态地给实例添加 magic method, 比如说

    from functools import partial
    class A(object):
        def __init__(self, x):
            self.val = x
            
    a = A(1)
    
    magic = lambda self: "self.val=%s"%self.val
    
    a.__str__ = partial(magic, a)
    
    

    期望能输出这样地结果

    print(str(a))	# self.val=1
    

    但实际地输出是

    print(str(a))	# <__main__.A object at 0x00000000037A0F60>
    

    而这么调是可以地

    print(a.__str__())	# self.val=1
    

    试过元类, 但是私有方法没办法继承, 所以也不行。 大佬们有没有思路。。。

    4 replies    2018-05-19 00:01:06 +08:00
    wcsjtu
        1
    wcsjtu  
    OP
       May 14, 2018
    ....打扰了, 用元类可以解决。。。。
    luzhongqiu
        2
    luzhongqiu  
       May 15, 2018
    确定不是 __unicode__? python3 才是__str__吧,我没试验,记得是这样。。放弃 py2 到 py3 吧。。。
    rookiebulls
        3
    rookiebulls  
       May 15, 2018
    partial(magic, a)是个函数啊
    gjquoiai
        4
    gjquoiai  
       May 19, 2018
    A.__str__ = magic
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   972 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 42ms · UTC 20:07 · PVG 04:07 · LAX 13:07 · JFK 16:07
    ♥ Do have faith in what you're doing.