V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
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
john990
V2EX  ›  Python

python 中两个大部分字段相同的类,值如何复制比较好

  •  
  •   john990 · Mar 1, 2015 · 3376 views
    This topic created in 4075 days ago, the information mentioned may be changed or developed.
    现在是在构造方法里挨个拷过去,有更好的方法吗?
    10 replies    2015-03-02 16:05:41 +08:00
    binux
        1
    binux  
       Mar 1, 2015
    既然是『大部分』而不是『全部』,除了挨个拷贝,还能怎么着?
    或许你可以写一个 attributes list 用 getattr, setattr
    9hills
        2
    9hills  
       Mar 1, 2015 via iPhone
    继承?
    9hills
        3
    9hills  
       Mar 1, 2015 via iPhone
    或者 组合。 两个类的成员大部分相同,试着抽象下
    ruoyu0088
        4
    ruoyu0088  
       Mar 1, 2015
    请帖程序
    tkliuxing
        5
    tkliuxing  
       Mar 1, 2015
    talk is cheap show me the code
    john990
        6
    john990  
    OP
       Mar 2, 2015
    @ruoyu0088
    @tkliuxing
    很简单的需求
    两个类:
    class A:
    field1
    field2

    class B:
    field_b
    field1
    field2

    其中A里的字段名B里面都有且相同,现在有A的实例,想把A和B相同字段的值赋给B
    ruoyu0088
        7
    ruoyu0088  
       Mar 2, 2015
    field1,2是在类下面定义的?还是在__init__中设置的?
    john990
        8
    john990  
    OP
       Mar 2, 2015
    @ruoyu0088 类下面定义的
    repus911
        9
    repus911  
       Mar 2, 2015
    如果你确定两边有一致性的话
    可以用__dict__查出A全部属性,然后检查B有没有,有的话赋值
    a = A()
    b = B()

    for key in a.__dict__:
    if key.statswith('__'):
    continue
    if callable(getattr(a, key, None)):
    continue
    setattr(b, key, getattr(a, key, None))
    ruoyu0088
        10
    ruoyu0088  
       Mar 2, 2015
    类下面定义的属性是类的属性,不是实例的,你确定这是你想要的吗,你还是把完整的程序贴出来。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5366 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 47ms · UTC 03:51 · PVG 11:51 · LAX 20:51 · JFK 23:51
    ♥ Do have faith in what you're doing.