V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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 · 2018-05-14 16:36:14 +08:00 · 1602 次点击
    这是一个创建于 2146 天前的主题,其中的信息可能已经有所发展或是发生改变。

    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 条回复    2018-05-19 00:01:06 +08:00
    wcsjtu
        1
    wcsjtu  
    OP
       2018-05-14 16:59:01 +08:00
    ....打扰了, 用元类可以解决。。。。
    luzhongqiu
        2
    luzhongqiu  
       2018-05-15 13:03:04 +08:00
    确定不是 __unicode__? python3 才是__str__吧,我没试验,记得是这样。。放弃 py2 到 py3 吧。。。
    rookiebulls
        3
    rookiebulls  
       2018-05-15 20:18:35 +08:00
    partial(magic, a)是个函数啊
    gjquoiai
        4
    gjquoiai  
       2018-05-19 00:01:06 +08:00
    A.__str__ = magic
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3372 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 10:42 · PVG 18:42 · LAX 03:42 · JFK 06:42
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.