Python 2类的继承

问题描述:

我是编程新手,我有一个关于继承和创建类的问题。我有一个班级“障碍”,其中有一些类型,如圆柱体和墙壁(编码为圆柱体(障碍)等)。我想为“障碍”做一个类,它本质上是一种类型的墙,但我希望代理人与他们以不同的方式进行交互,就像他们对墙进行交互一样。我的wall类在其初始化方法/函数中定义了不同的变量,我对我在创建屏障(Wall)时必须指定的内容感到困惑 - 我必须复制到屏障(Wall)的所有x1 =打开或者将这些文件自动复制。Python 2类的继承

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

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" 
+0

dunder str是不缩进正确的(因为它是现在不是类墙的一部分) 。 – narn

+0

对不起,谢谢!当我复制它时有一些缩进问题! @narn – Pue

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

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) 

问题:......我必须复制...所有的X1的=和等,或将这些被复制自动

所述VARS x1, y1, x2, y2temporary localself.__init__丢失后返回。

这是没有必要的瓦尔,实现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