推荐学习书目
› 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
lynn0977
V2EX  ›  Python

python2 怎么继承多个不确定数量的类

  •  
  •   lynn0977 · Oct 23, 2020 · 2662 views
    This topic created in 2170 days ago, the information mentioned may be changed or developed.
    需求是想继承多个类,但是类的数量不确定。
    对于 python3,可以直接把要继承的类放到一个列表中如 cls,然后按如下的方法继承:
    class NewClass(*cls):
    def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)

    对于 python2.7 按照这个写法好像是不行的,报错了,问一下 python2.7 要如何实现这个目的。
    4 replies  •  2020-10-23 10:18:41 +08:00
    mec
        1
    mec  
       Oct 23, 2020
    啊 这也行,太 magic 了 感觉类的继承最好还是更显式一些吧
    chogath
        2
    chogath  
       Oct 23, 2020
    用装饰器实现不行嘛,你这整的是啥
    Wincer
        3
    Wincer  
       Oct 23, 2020
    Python2 也可以做到,但是比较麻烦:
    1. 首先把 cls 里面的所有类改成新式类;
    2. 使用 type('NewClass', cls, attr) 的方式创建。

    ```
    class A(object):
    pass
    class B(object):
    pass
    class C(object):
    pass

    cls = (A, B, C)

    def init(self, *args, **kwargs):
    super(cls[0], self).__init__(*args, **kwargs)

    type('E', cls, dict(__init__=init)) # 这样可以创建
    >>> __main__.E
    ```

    但是不太建议这么做,,你也看到代码多么复杂了,type 动态创建的类也不好 debug 。
    xiaolinjia
        4
    xiaolinjia  
       Oct 23, 2020
    用 types 函数创建类呗
    NewClass = type('NewClass', tuple(cls), class_attrs)
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2554 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 03:43 · PVG 11:43 · LAX 20:43 · JFK 23:43
    ♥ Do have faith in what you're doing.