2017-07-14 99 views
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

回答

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) 
0

問題:......我必須複製...所有的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