具有父实例的Init子项 [英] Init child with Parent instance

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

问题描述

我有一个函数返回类Parent的实例:

  def generateParent():
do_stuff
return Parent(some_parameters)



现在我想要初始化Parent的子类,调用 generateParent()

  
def __new __():
return generateParent(some_other_parameters)

,当我覆盖从Parent在Child的一些方法,然后在我的程序中的Child的实例中调用它们,将调用原始的Parent方法,而不是来自Child的新方法。我在这里做错了吗?我在这里为我的任务使用正确的设计?



编辑:我没有访问Parent或generateParent()



解决方案(感谢@Paul McGuire的回答):



  class Child(object):
def __init __(self):
self.obj = generateParent()

def __getattr __(self,attr):
return getattr(self.obj,attr)
c>

不是你的代码,那么你可能想使用containment和委托代替继承。也就是说,不是定义一个子类,而是定义一个包含生成对象的包装类,在需要时转发方法调用,但可以在包装器中添加新的行为或修改的行为。



这个问题,OP有一个类似的情况,有一个类在一个库中生成,但想要扩展类和/或修改类的一些行为。看看我在这个问题中添加了一个包装类,你可能会考虑做类似的事情。


I have a function which return instances of the class Parent:

def generateParent():
   do_stuff
   return Parent(some_parameters)

Now I want to init a subclass of Parent with the results of a call to generateParent():

class Child(Parent):
    def __new__():
        return generateParent(some_other_parameters) 

The problem is, when I override some methods from Parent in Child and then call them in instances of Child in my program, the original Parent method gets called instead of the new one from Child. Am I doing something wrong here? Am I using the correct design here for my task?

EDIT: I don't have access neither to Parent nor generateParent()

Solution(thanks to @Paul McGuire's answer):

class Child(object):
    def __init__(self):
        self.obj = generateParent()

    def __getattr__(self, attr):
        return getattr(self.obj, attr)

解决方案

Since generateParent is not your code, then instead of inheritance, you might want to use containment and delegation. That is, instead of defining a subclass, define a wrapper class that contains the generated object, forwards method calls to it when needed, but can add new behavior or modified behavior in the wrapper.

In this question, the OP had a similar situation, having a class generated in a libary, but wanting to extend the class and/or modify some behavior of the class. Look at how I added a wrapper class in that question, and you might consider doing something similar here.

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

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