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

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

  •  
  •   lynn0977 · 2020-10-23 09:20:39 +08:00 · 1510 次点击
    这是一个创建于 1253 天前的主题,其中的信息可能已经有所发展或是发生改变。
    需求是想继承多个类,但是类的数量不确定。
    对于 python3,可以直接把要继承的类放到一个列表中如 cls,然后按如下的方法继承:
    class NewClass(*cls):
    def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)

    对于 python2.7 按照这个写法好像是不行的,报错了,问一下 python2.7 要如何实现这个目的。
    4 条回复    2020-10-23 10:18:41 +08:00
    mec
        1
    mec  
       2020-10-23 10:00:30 +08:00
    啊 这也行,太 magic 了 感觉类的继承最好还是更显式一些吧
    chogath
        2
    chogath  
       2020-10-23 10:03:10 +08:00
    用装饰器实现不行嘛,你这整的是啥
    Wincer
        3
    Wincer  
       2020-10-23 10:18:16 +08:00
    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  
       2020-10-23 10:18:41 +08:00
    用 types 函数创建类呗
    NewClass = type('NewClass', tuple(cls), class_attrs)
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5434 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 08:47 · PVG 16:47 · LAX 01:47 · JFK 04:47
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.