相关疑难解决方法(0)

如何从Python中预先存在的类实例继承?

我有一堂课Parent

class Parent:
    def __init__(self, foo):
        self.foo = foo
Run Code Online (Sandbox Code Playgroud)

然后我有另一个Child扩展的类Parent。但我想Child获取一个预先存在的实例parent并将其用作要继承的父实例(而不是创建Parent具有相同构造函数参数的新实例)。

class Child(Parent):
    def __init__(self, parent_instance):
        """ Do something with parent_instance to set this as the parent instance """

    def get_foo(self):
        return self.foo
Run Code Online (Sandbox Code Playgroud)

然后我理想地能够做到:

p = Parent("bar")
c = Child(p)

print(c.get_foo()) # prints "bar"
Run Code Online (Sandbox Code Playgroud)

python oop inheritance python-3.x

5
推荐指数
1
解决办法
1714
查看次数

从实例而不是类继承 [Python 3]

我想启动子类的多个实例,每个子类从类的特定实例而不是通用类中获取属性。

例如,如果我有建筑物和房间,则每个房间都需要属于建筑物的特定实例,并采用其属性和方法。

class Building:
     def __init__(self, buildingName, location):
        self.buildingName = buildingName
        self.location = location
        # lots more intersting stuff

    def Evacuate_Building(self):
        # do some stuff
        pass

class Room(Building):
     def __init__(self, roomName, roomType):
        self.roomName = roomName
        self.roomType = roomType
        # lots more intersting stuff

    def Directions(self, Current_Location):
        '''do some stuff involving this.roomName and this.location which comes from the specific instance of the class'''
        pass
Run Code Online (Sandbox Code Playgroud)

假设我有三栋建筑:“北”、“南”和“西”。

每栋楼都有自己的房间。

仅看北楼,它有“N1”、“N2”、“N3”、“N4”房间。

在我的代码中,我将首先遍历并启动三座建筑物,然后我将启动房间,以某种方式将它们链接回其相应的建筑物。

这允许我使用 Directions 方法,该方法利用其父类实例的属性位置,该属性对于该建筑物来说是唯一的,而不是一般值。它还需要能够使用父类 Evacuate_Building 中的方法。

每次我使用 super(buildingName, location) 或 Building.__ init__(self,buildingName, location) 在更标准的设置中启动一个房间时,我可以通过传递位置数据来解决这个问题,但这意味着我必须编写位置每个房间,如果我在建筑物中添加或更改某些内容,如果添加了其他属性,我需要更改每个房间的初始化和初始化代码。 …

python oop inheritance class

4
推荐指数
1
解决办法
1595
查看次数

使用父实例初始化子实例

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

def generateParent():
   do_stuff
   return Parent(some_parameters)
Run Code Online (Sandbox Code Playgroud)

现在我想用调用的结果来初始化 Parent 的子类generateParent()

class Child(Parent):
    def __new__():
        return generateParent(some_other_parameters) 
Run Code Online (Sandbox Code Playgroud)

问题是,当我重写 Child 中 Parent 的某些方法,然后在程序中的 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)
Run Code Online (Sandbox Code Playgroud)

python inheritance initialization class

3
推荐指数
1
解决办法
3672
查看次数

标签 统计

inheritance ×3

python ×3

class ×2

oop ×2

initialization ×1

python-3.x ×1