继承Python中的实例 [英] Inheriting from instance in Python

查看:199
本文介绍了继承Python中的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,我想直接从Parent类的实例构造一个Child类的实例。例如:

In Python, I would like to construct an instance of the Child's class directly from an instance of the Parent class. For example:

A = Parent(x, y, z)
B = Child(A)

这是我认为可行的黑客攻击:

This is a hack that I thought might work:

class Parent(object):

    def __init__(self, x, y, z):
        print "INITILIZING PARENT"
        self.x = x
        self.y = y
        self.z = z

class Child(Parent):

    def __new__(cls, *args, **kwds):
        print "NEW'ING CHILD"
        if len(args) == 1 and str(type(args[0])) == "<class '__main__.Parent'>":
            new_args = []
            new_args.extend([args[0].x, args[0].y, args[0].z])
            print "HIJACKING"
            return Child(*new_args)
        print "RETURNING FROM NEW IN CHILD"
        return object.__new__(cls, *args, **kwds)

但是当我跑步时

B = Child(A) 

我得到:

NEW'ING CHILD  
HIJACKING  
NEW'ING CHILD  
RETURNING FROM NEW IN CHILD  
INITILIZING PARENT  
Traceback (most recent call last):  
  File "classes.py", line 52, in <module>  
    B = Child(A)  
TypeError: __init__() takes exactly 4 arguments (2 given) 

看起来hack的工作方式与我预期的一样,但编译器最后会抛出一个TypeError。我想知道我是否可以重载TypeError使其忽略B = Child(A)成语,但我不知道该怎么做。在任何情况下,你能否告诉我你从实例继承你的解决方案?

It seems the hack works just as I expected but the compiler throws a TypeError at the end. I was wondering if I could overload TypeError to make it ignore the B = Child(A) idiom but I wasn't sure how to do that. In any case, would you please give me your solutions for inheriting from instances?

谢谢!

推荐答案

一旦 __ new __ 在类 Child 中返回的实例> Child 将调用子.__ init __ (使用相同的参数 __ new __ )那个实例 - 显然它只是继承了 Parent .__ init __ ,只用一个arg(另一个 Parent A )。

Once __new__ in class Child returns an instance of Child, Child.__init__ will be called (with the same arguments __new__ was given) on that instance -- and apparently it just inherits Parent.__init__, which does not take well to being called with just one arg (the other Parent, A).

如果没有其他方式可以创建子,你可以定义一个 Child .__ init __ ,它接受一个arg(它忽略)或三个(在这种情况下它调用) 父.__初始化__ )。但放弃 __ new __ 更简单,并且在 Child .__ init __ 中拥有所有逻辑,只需调用 Parent .__ init __ 恰当!

If there is no other way a Child can be made, you can define a Child.__init__ that accepts either one arg (which it ignores) or three (in which case it calls Parent.__init__). But it's simpler to forego __new__ and have all the logic in Child.__init__, just calling the Parent.__init__ appropriately!

使用代码示例来说明这一点:

To make this concrete with a code example:

class Parent(object):

    def __init__(self, x, y, z):
        print "INITIALIZING PARENT"
        self.x = x
        self.y = y
        self.z = z

    def __str__(self):
        return "%s(%r, %r, %r)" % (self.__class__.__name__,
            self.x, self.y, self.z)


class Child(Parent):

    _sentinel = object()

    def __init__(self, x, y=_sentinel, z=_sentinel):
        print "INITIALIZING CHILD"
        if y is self._sentinel and z is self._sentinel:
            print "HIJACKING"
            z = x.z; y = x.y; x = x.x
        Parent.__init__(self, x, y, z)
        print "CHILD IS DONE!"

p0 = Parent(1, 2, 3)
print p0
c1 = Child(p0)
print c1
c2 = Child(4, 5, 6)
print c2

这篇关于继承Python中的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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