【问题标题】:Python automation: class and subclass 'AttributeError'Python 自动化:类和子类 'AttributeError'
【发布时间】:2014-03-10 22:25:48
【问题描述】:

我正在使用 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: 'instrument' object has no attribute 'component1'

【问题讨论】:

    标签: python class subclass attributeerror


    【解决方案1】:

    您不需要通过instrument 访问component1 类。干脆做

    I = instrument()
    comp = component1() 
    

    您所做的是访问您的instrument 实例(不存在)的component1 属性,而不是实例化新的component1

    【讨论】:

      【解决方案2】:

      component1instrument 的子类型,因此要创建component1 对象,您只需要创建它即可。您尤其不需要有一个 instrument 对象来创建它:

      comp = component1()
      comp.function1()
      comp.function2()
      

      它不需要知道实际上涉及到一个基类型。

      【讨论】:

        【解决方案3】:

        只要做:

        comp = component1()
        

        component1 不是仪器类的一部分,而是从它派生的类(因此它是“特殊”仪器)。 此外,最好将类名大写 => Instrument, Compoment

        【讨论】:

        • 成功了!谢谢。此外,现在看来 init 函数不是必需的。我是否只在我希望类在每次调用时执行某些操作时才使用 init
        • 一个没有任何东西的初始化(只是pass)实际上什么都不做,所以你可以删除它。调用 super 的 init 是一个好主意,但如果您不完全知道基类型的 init 是否执行任何操作。
        • 您在需要自定义构造函数时使用 init,即初始化您正在创建的 object 的某些属性。这个 objectclassinstance,您可以在其中定义 init。但这超出了这个问题,你会更好地阅读关于 python 中面向对象编程的好教程。总帐。
        猜你喜欢
        • 2013-10-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多