Python2类继承
我是编程新手,我有一个关于继承和创建类的问题。我有一个“障碍物”类,其中有圆柱体和墙(编码为圆柱体(障碍物)等)。我想为“屏障”创建一个类,它本质上是墙的一种类型,但我希望代理与它们进行不同的交互,就像它们与墙交互一样。我的wall类在其初始化方法/函数中定义了不同的变量,我对创建barrier(wall)时必须指定的内容感到困惑-我必须复制barrier(wall)所有的x1=等等,还是自动复制它们 下面我介绍了wall类中的一些内容(不是所有内容),只是为了说明第一个方法中定义的变量的含义Python2类继承,python,class,inheritance,Python,Class,Inheritance,我是编程新手,我有一个关于继承和创建类的问题。我有一个“障碍物”类,其中有圆柱体和墙(编码为圆柱体(障碍物)等)。我想为“屏障”创建一个类,它本质上是墙的一种类型,但我希望代理与它们进行不同的交互,就像它们与墙交互一样。我的wall类在其初始化方法/函数中定义了不同的变量,我对创建barrier(wall)时必须指定的内容感到困惑-我必须复制barrier(wall)所有的x1=等等,还是自动复制它们 下面我介绍了wall类中的一些内容(不是所有内容),只是为了说明第一个方法中定义的变量的含义
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"
如果我正确理解了您的问题,您不应该将任何变量复制到子类,您的变量将被继承。类变量将是相同的,并且您将能够在子类的实例化期间设置实例变量。考虑这个代码:
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=等等,还是会自动复制
变量x1、y1、x2、y2
为临时本地变量
至self.\uuu初始变量
,返回后丢失
如果根本不需要VAR,请实现一个属性定义坐标(…
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
dunder str缩进不正确(因为它现在不是类墙的一部分)。是的,对不起,谢谢!我复制它时遇到了一些缩进问题!@narn