Python 2类继承

时间:2017-07-14 13:50:56

标签: python class inheritance

我是编程新手,我对继承和创建类有疑问。我有一个类"障碍",其中有类型,如圆柱和墙壁(编码为圆柱体(障碍物)等)。我想为"障碍"做一个班级。这本质上是一种墙,但我希望代理能够与墙壁进行不同的交互。我的墙类在其初始化方法/函数中定义了不同的变量,并且我在创建屏障时需要指定的内容(Wall) - 我是否必须复制到屏障(Wall)所有的x1 =等等,或将自动复制。

下面我已经介绍了墙类中的一些内容(不是所有内容),只是为了说明第一种方法中定义的变量的含义。

class Wall(Obstacle):
""" Class representing a Wall obstacle. """

    def __init__(self, origin, end, detection=9.):
        self.type = 'wall'
        self.origin = origin
        self.end = end
        self.detection = detection

        x1 = self.origin[0]
        y1 = self.origin[1]
        x2 = self.end[0]
        y2 = self.end[1]

    def __str__(self):
        return "Wall obstacle"

2 个答案:

答案 0 :(得分:0)

如果我理解你的问题,你不应该将任何变量复制到子类,你的变量将被继承。类变量将是相同的,您将能够在子实例化期间设置实例变量。请考虑以下代码:

class Test1():
    test2 = 'lol2'  # class variable shared by all instances

    def __init__(self, test):
        self.test = test  # instance variable unique to each instance
        test3 = self.test  # just useless variable not assigned to class or instance


class Test2(Test1):
    pass


t = Test2('lol')
print(t.test)  # lol
print(t.test2)  # lol2
print(dir(t))  # ['__doc__', '__init__', '__module__', 'test', 'test2']

t = Test2('foo')
print(t.test)  # foo
print(t.test2)  # lol2
print(dir(t))  # ['__doc__', '__init__', '__module__', 'test', 'test2']

所以我觉得你应该这样做:

class Wall(Obstacle):

    def __init__(self, _type, origin, end, detection=9.):
        self.type = _type
        self.origin = origin
        self.end = end
        self.detection = detection

        self.x1 = self.origin[0]
        self.y1 = self.origin[1]
        self.x2 = self.end[0]
        self.y2 = self.end[1]

    def __str__(self):
        return "Wall obstacle"


class Barrier(Wall):

    def __str__(self):
        return "Barrier obstacle"


_type = 'barrier'
origin = ...
end = ... 
detection = ...

bar = Barrier(_type, origin, end, detection)

答案 1 :(得分:0)

  

问题:...我是否必须复制...所有x1 =等等,或者是否会自动复制

Vars x1, y1, x2, y2temporary localself.__init__,返回后丢失

根本不需要Vars,实现property def coordinate(...

class Wall(Obstacle):
    ...

    @property
    def coordinate(self):
        return (self.origin[0], self.origin[1], self.end[0], self.end[1])

<强>用法

wall = Wall((1,2),(1,2) )
x1, y1, x2, y2 = wall.coordinate