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
singed
V2EX  ›  Python

分享一段代码, a 对象与 b 对象具有相同属性名的赋值

  •  1
     
  •   singed · 2018-07-07 16:06:41 +08:00 · 2161 次点击
    这是一个创建于 2113 天前的主题,其中的信息可能已经有所发展或是发生改变。
    def copy_attr(src, dest, lst):
    for x in lst:
    setattr(dest, x, getattr(src, x))

    a = A()
    b = B()

    a.x = b.x
    a.y = b.y
    a.z = b.z

    lst = ["x", "y", "z"]
    copy_attr(a, b, lst)

    函数作用, 将 8,9,10 行的代码 写成 12, 13 行的样子.
    9 条回复    2018-07-09 22:27:37 +08:00
    tkmiles
        1
    tkmiles  
       2018-07-07 18:16:57 +08:00
    所以, 你的异常呢?
    singed
        2
    singed  
    OP
       2018-07-07 19:18:35 +08:00
    @tkmiles 没懂你意思, 那个函数就 3 行代码, 出异常也就只有 no field "y" in a object 对象这种, 还需要对异常进行什么处理吗?
    whoami9894
        3
    whoami9894  
       2018-07-08 18:02:15 +08:00
    就是 Python 的反射写了个循环....为什么要分享
    xpresslink
        4
    xpresslink  
       2018-07-08 22:55:50 +08:00
    谢谢楼主不辞辛苦从火星赶来告诉大家大清亡了。
    singed
        5
    singed  
    OP
       2018-07-09 10:17:08 +08:00
    @whoami9894 @xpresslink 对于现在的你们来说, 什么东西值得分享? 什么东西不值得分享?
    xxxy
        6
    xxxy  
       2018-07-09 11:15:40 +08:00
    zan
    xpresslink
        7
    xpresslink  
       2018-07-09 11:24:00 +08:00
    @singed 确实没有什么值得分享的了,我们到这里来只是为了扯蛋的:-)。

    碰到问题,我会直接去看 python 源码
    https://github.com/python/cpython

    推荐你看看这个
    https://github.com/jobbole/awesome-python-cn
    你有什么自己写的东西超出这个范围的可以分享一下。
    singed
        8
    singed  
    OP
       2018-07-09 15:11:21 +08:00
    @xpresslink 谢谢你的链接, 只是这种海量的资料总是让我感到迷茫. 我也不会 C 语言, 我只是来这论坛泡一泡, 前几天刚注册的账号
    xpresslink
        9
    xpresslink  
       2018-07-09 22:27:37 +08:00
    @singed 多泡一泡在说吧,在 V2EX 想 B 是很难的,因为都是高水平的喷子。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1129 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 23:40 · PVG 07:40 · LAX 16:40 · JFK 19:40
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.