Python多重继承:动态进行操作有什么问题? [英] Python multiple inheritance: Whats wrong doing it dynamically?

查看:96
本文介绍了Python多重继承:动态进行操作有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基于此答案__new____init__应该如何在Python中工作,

Based on this answer, of how __new__ and __init__ are supposed to work in Python,

我编写了这段代码来动态定义和创建新的类和对象.

I wrote this code to dynamically define and create a new class and object.

class A(object):
    def __new__(cls):
      class C(cls, B):
          pass
      self = C()
      return self

    def foo(self):
      print 'foo'

class B(object):
    def bar(self):
      print 'bar'

a = A()
a.foo()
a.bar()

基本上,因为A的__new__返回继承了A和B的动态创建的C,所以它应该具有属性bar.

Basically, because the __new__ of A returns a dynamically created C that inherits A and B, it should have an attribute bar.

为什么C 没有具有bar属性?

推荐答案

解决无限递归:

Resolve the infinite recursion:

class A(object):
  def __new__(cls):
    class C(cls, B):
      pass
    self = object.__new__(C)
    return self

(感谢 balpha 用于指出实际问题.)

(Thanks to balpha for pointing out the actual question.)

这篇关于Python多重继承:动态进行操作有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆