我正在使用Python自动化一个工具,但我对使用Python进行面向对象编程还很陌生。我想创建几个类:一个用于仪器的超类和几个用于控制仪器的特定组件(控制器、传感器等)的子类。
class instrument(object):
def __init__(self):
pass
def function1(self):
print 'Do something'
class component1(instrument):
def __init__(self):
super(component1, self).__init__()
def function2(self):
print 'Do something to component 1'但是,当我尝试调用component1时:
I = instrument()
comp = I.component1()我得到一个AttributeError:
AttributeError: 'instrument' object has no attribute 'component1'发布于 2014-03-11 06:28:52
您不需要通过instrument one访问component1类。简单地做
I = instrument()
comp = component1() 您所做的是访问instrument实例的component1属性(该属性不存在),而不是实例化新的component1。
发布于 2014-03-11 06:28:52
component1是instrument的一个子类型,所以要创建component1对象,您只需要创建它。你尤其不需要有一个instrument对象来创建它:
comp = component1()
comp.function1()
comp.function2()它不需要知道实际上涉及到一个基类型。
发布于 2014-03-11 06:30:27
只需这样做:
comp = component1()component1不是instrument类的一部分,而是从它派生的类(所以它是“特殊”的工具)。此外,将类名大写为=> Instrument、Compoment也是一个好主意
https://stackoverflow.com/questions/22312667
复制相似问题