【问题标题】:Beginner python error - no attribute found初学者python错误 - 找不到属性
【发布时间】:2014-12-25 18:13:15
【问题描述】:

我有这个类 bgp_route:

class bgp_route:
    def _init_(self, path):
        self.nextHop = None
        self.asPath = ''
        self.asPathLength = 0
        self.routePrefix = None

但是,当我运行以下测试代码时;

from bgp_route import bgp_route

testRoute =  bgp_route()

testRoute.asPath += 'blah'
print testRoute.asPath

我收到以下错误:

   Traceback (most recent call last):
      File "testbgpRoute.py", line 6, in <module>
        testRoute.asPath += 'blah'
    AttributeError: bgp_route instance has no attribute 'asPath'

这个错误的原因是什么? bgp_route的实例化不应该将属性asPath初始化为空字符串吗?

【问题讨论】:

  • 你需要__init__ 而不是_init_

标签: python class attributes


【解决方案1】:

你拼错了__init__

def _init_(self, path):

两端需要两个下划线。由于没有使用正确的名称,Python 永远不会调用它,并且永远不会执行 self.asPath 属性分配。

请注意,该方法需要 path 参数;您需要在构造实例时指定该参数。由于您的__init__ 方法否则忽略此参数,您可能想要删除它:

class bgp_route:
    def __init__(self):
        self.nextHop = None
        self.asPath = ''
        self.asPathLength = 0
        self.routePrefix = None

【讨论】:

  • 可能也应该添加对象
  • @PadraicCunningham 不确定此时引入该概念是否有帮助。
【解决方案2】:

它叫做__init__,两边有两个下划线,就像任何其他python魔术方法一样。

顺便说一句,您的构造函数需要一个 path 参数。

【讨论】:

    猜你喜欢
    • 2013-04-18
    • 1970-01-01
    • 1970-01-01
    • 2020-05-09
    • 2017-09-20
    • 2015-07-08
    • 2023-03-14
    • 2010-11-25
    相关资源
    最近更新 更多