Python:从派生类获取基类值 [英] Python: Getting baseclass values from derived class

查看:80
本文介绍了Python:从派生类获取基类值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

希望这很清楚:

class myParent():
    def __init__( self ):
        self.parentNumber = 5

class Child( myParent ):
    def __init__( self ):
        self.childNumber = 4

    def multiplyNumbers( self ):
        print myParent.parentNumber * self.childNumber

p = Child()
p.multiplyNumbers()

我希望分别设置parentNumber,然后通过子类获得该数字,在这种情况下,将其用于乘法.

I wish to set the parentNumber individually, and then reach that number via the child class, and in this case use it for some multiplication.

我是OOP领域的新手,所以也欢迎任何有关继承的通用指针!

I'm new to the OOP area so any general pointers on inheritance is welcome as well!

更多信息: 我正在为基于vfx的项目设计项目管理解决方案,并且正在研究类和继承,以了解它们如何对我有最大的帮助.

More info: I'm designing a project management solution for vfx-based projects, and am playing with classes and inheritance to see how they can help me the most.

现在,我有顶级课程Project和派生课程Shot.镜头具有一个self.length变量,该变量具有特定镜头的长度.它还有一个getLengthInSeconds()方法,该方法使用self.length和Project.fps来确定长度(以秒为单位). Project具有setFps()方法,该方法在创建类的实例之后设置fps.

Right now, I've got the top class, Project, and a derived class, Shot. Shot has a self.length variable with the length of the specific shot. It's also got a getLengthInSeconds() method that uses self.length along with the Project.fps to determine the length in seconds. Project has a setFps() method in which the fps is set after an instance of the class is created.

我有点习惯以self为前缀的变量.并且没有在没有self的情况下对使用更多全局"变量的类进行过多试验. .如果我将所有内容都全球化,那么我可以轻松使用Project.fps,但是我的脖子上收到了不良编程习惯"警告.也许有更好,更整洁的方法吗?

I'm kind of used to variables being prefixed with self. and have not experimented much with classes using the more "global" variables without self. . If I make everything global, no self., I can use Project.fps without hassle, but I'm getting a "bad programming practice" warning in my neckhair. Perhaps there is a better, more neat, way?

经过一番阅读,super()似乎有点危险,而且超出了我的想象.我主要是单继承类,甚至不确定如何使用菱形层次结构.是否有更安全的方法来访问不包含super()的超类变量和方法?

After some reading, super() seems kinda dangerous, and a bit more than I need I think. I am mainly having single-inheritance classes and aren't even sure how to make use of diamond hierarchies.. Is there a safer way to access superclass variables and methods that doesn't include super()?

好吧,看看这是否有意义,或者我是否正在考虑全部错误.

Allright, see if this makes sense or if I'm thinking about it all wrong.

我正在将类和继承视为群体和孩子.一个孩子知道它是父母和所有的价值观.另一个父母的孩子知道父母的价值观.我要完成的工作是将所有镜头创建为项目的一部分.现在,我要在Project()类中创建Shot()实例,然后将这些实例添加到镜头列表中,然后在Project()实例中进行维护.

I'm looking at classes and inheritance as groups and children. A child knows it's parent and all it's values. A child to another parent knows That parents values. What I'm trying to accomplish is having all shots created be part of a project. And right now, I'm creating Shot() instances from within Project() class, adding the instances to a list of shots which is then maintained within the Project() instance.

class myParent( object ):
    def __init__( self ):
        self.parent_id = ''
        self.children = []

    def createChild( self, name ):
        self.children.append( myChild( name ) )

    def getChildren( self ):
        return self.children

    def setParentId( self, id ):
        self.parentId = id

class myChild( myParent ):
    def __init__( self, id ):
        super(myChild, self).__init__()
        self.id = id

    def getParentId( self ):
        return self.parent_id

p = myParent()
p.setParentId( 'parent01' )
p.createChild( 'child01' )
print p.getChildren()[0].getParentId()

我可以在这里看到逻辑上的错误步骤,但是没有真正的解决方法. 似乎每个孩子都以这种方式获取父对象的新实例,其中parent_id始终是一个空字符串.

I can sort of see the mis-steps in logic here, but no real way around it.. Seems like every child is getting a new instance of the parent this way, where parent_id is always an empty string.

推荐答案

class myParent( object ):
    def __init__( self ):
        self.parentNumber = 5

class Child( myParent ):
    def __init__( self ):
        myParent.__init__( self )
        self.childNumber = 4

    def multiplyNumbers( self ):
        print self.parentNumber * self.childNumber

p = Child()
p.multiplyNumbers()

在没有多重继承或其他边界情况的情况下,通常可以在没有super的情况下很好地进行管理,尽管如果基类发生了变化,您将需要记住将父类的名称从 init (以及任何其他显式引用myParent的方法).

You can usually manage just fine without super when you don't have multiple inheritance or other border cases, although if the base class changes, you will need to remember to change the parent class name from init (and any other method that refers to myParent explicitly).

如果父母的__init__ 接受参数,则需要从孩子的__init__传递参数.

If your parent's __init__ takes parameters, you need to pass them on from the child's __init__.

class myParent( object ):
    def __init__( self, customParam ):
        self.parentNumber = 5
        self.customParam = customParam

class Child( myParent ):
    def __init__( self, customParam ):
        myParent.__init__( self, customParam )
        self.childNumber = 4

如果您不喜欢在所有子类中都重复执行customParam,则有一个替代的OO模式,称为两阶段构造,其工作方式如下:

If you dislike the repetition of customParam in all child classes, there's an alternative OO pattern called two phase construction, which works like this:

class myParent( object ):
    def customInit( self, customParam ):
        self.parentNumber = 5
        self.customParam = customParam

class Child( myParent ):
    def __init__( self, customParam ):
        self.childNumber = 4

p = Child()
p.customInit(10)
p.multiplyNumbers()

在这种模式下,您无需重复任何父级参数,甚至无需在子级中调用父级的__init__,但缺点是您需要记住在创建时始终调用辅助构造函数对象,否则您的对象将部分未初始化.

In this pattern, you don't need to repeat any of the parent's parameters, or even call the parent's __init__ in the child, but the downside is that you will need to remember to always call the secondary constructor when creating objects, or your object will be left partially uninitialized.

更新(回答更新后的问题):

UPDATE (to answer the updated question):

您似乎在这里混淆了两个不相关的育儿概念.继承是关于类型层次结构的,您似乎追求所有权层次结构(is-a与has-a).

You seem to be mixing two unrelated concepts of parenthood here. Inheritance is about type hierarchy, and you seem to be after an ownership hierarchy (is-a versus has-a).

我会这样构造您的更新代码:

I would structure your updated code like this:

class myParent( object ):
    def __init__( self, parentId ):
        self.id = parentId
        self.children = []

    def createChild( self, name ):
        self.children.append( myChild( name, self ) )

    def getChildren( self ):
        return self.children

class myChild( object ):
    def __init__( self, childId, parent ):
        self.id = childId
        self.parent = parent

    def getParentId( self ):
        return self.parent.id

p = myParent( 'parent01' )
p.createChild( 'child01' )
print p.getChildren()[0].getParentId()

这篇关于Python:从派生类获取基类值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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