Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 访问超类中的属性_Python_Python 2.7_Inheritance - Fatal编程技术网

Python 访问超类中的属性

Python 访问超类中的属性,python,python-2.7,inheritance,Python,Python 2.7,Inheritance,我正在构建一棵树和一个字典,将树中的节点映射到唯一的ID。尝试访问字典中的对象时,我遇到了一些意外行为。我可以访问对象的某些继承属性,但不能访问其他属性。我提取了项目的一部分,并对其进行了修改,希望能够理解: #!/usr/bin/env python IMPORTS = vars() class Node(object): SYMTAB = {} def __init__(self, kwargs={}): self.ati = kwargs.get(u'@

我正在构建一棵树和一个字典,将树中的节点映射到唯一的ID。尝试访问字典中的对象时,我遇到了一些意外行为。我可以访问对象的某些继承属性,但不能访问其他属性。我提取了项目的一部分,并对其进行了修改,希望能够理解:

#!/usr/bin/env python

IMPORTS = vars()

class Node(object):
    SYMTAB = {}
    def __init__(self, kwargs={}):
        self.ati = kwargs.get(u'@i')
        self._add_symbol(self.ati, self)
        self.atr = kwargs.get(u'@r')

    def _add_symbol(self, k, v):
        self.SYMTAB[k] = v

class CompilationUnit(Node):
    def __init__(self, kwargs={}):
        super(CompilationUnit, self).__init__(kwargs)
        self.types = map(lambda x: IMPORTS[x['@t']](x),
                      kwargs.get('types').get('@e', []))

class BodyDeclaration(Node):
    def __init__(self, kwargs={}):
        super(BodyDeclaration, self).__init__(kwargs)

class TypeDeclaration(BodyDeclaration):
    def __init__(self, kwargs={}):
        super(TypeDeclaration, self).__init__(kwargs)
        self.members = map(lambda x: IMPORTS[x[u'@t']](x),
                        kwargs.get(u'members').get(u'@e', []))

class ClassOrInterfaceDeclaration(TypeDeclaration):
    def __init__(self, kwargs={}):
        super(ClassOrInterfaceDeclaration, self).__init__(kwargs)

class FieldDeclaration(BodyDeclaration):
    def __init__(self, kwargs={}):
        super(FieldDeclaration, self).__init__(kwargs)
        print '*'*10, 'SYMTAB:'
        for k,v in self.SYMTAB.items():
            print k,v
        print '*'*10
        print 'SYMTAB[self.atr]:',self.SYMTAB[self.atr]
        print self.SYMTAB[self.atr].atr
        print self.SYMTAB[self.atr].members

d = {u'@i': 0, u'@r': None, u'@t': u'CompilationUnit', 'types':
     {u'@e':
      [{u'@t': u'ClassOrInterfaceDeclaration', u'@i': 1, u'@r': 0,
        u'members':
        {u'@e':
         [{u'@t': 'FieldDeclaration', u'@i': 2, u'@r': 1}]}}]}}

c = CompilationUnit(d)
print c
这将产生以下输出:

********** SYMTAB:
0 <__main__.CompilationUnit object at 0x105466f10>
1 <__main__.ClassOrInterfaceDeclaration object at 0x10547c050>
2 <__main__.FieldDeclaration object at 0x10547c150>
**********
SYMTAB[self.atr]: <__main__.ClassOrInterfaceDeclaration object at 0x10547c050>
0
Traceback (most recent call last):
  File "class_error.py", line 74, in <module>
    c = CompilationUnit(d)
  File "class_error.py", line 30, in __init__
    kwargs.get('types').get('@e', []))
  File "class_error.py", line 29, in <lambda>
    self._types = map(lambda x: IMPORTS[x['@t']](x),
  File "class_error.py", line 54, in __init__
    super(ClassOrInterfaceDeclaration, self).__init__(kwargs)
  File "class_error.py", line 45, in __init__
    kwargs.get(u'members').get(u'@e', []))
  File "class_error.py", line 44, in <lambda>
    self._members = map(lambda x: IMPORTS[x[u'@t']](x),
  File "class_error.py", line 65, in __init__
    print self.SYMTAB[self.atr].members
AttributeError: 'ClassOrInterfaceDeclaration' object has no attribute 'members'
**********符号选项卡:
0
1.
2.
**********
符号表[self.atr]:
0
回溯(最近一次呼叫最后一次):
文件“class_error.py”,第74行,在
c=编译单元(d)
文件“class_error.py”,第30行,在uu init中__
kwargs.get('types').get('@e',[]))
文件“class_error.py”,第29行,在
self._types=map(lambda x:IMPORTS[x['@t']](x),
文件“class_error.py”,第54行,在uu init中__
super(类或接口声明,self)。\uuuu init\uuuuu(kwargs)
文件“class_error.py”,第45行,在uu init中__
kwargs.get(u'members').get(u'@e',[]))
文件“class_error.py”,第44行,在
self._members=map(lambda x:IMPORTS[x[u'@t']](x),
文件“class_error.py”,第65行,在uu init中__
打印self.SYMTAB[self.atr].members
AttributeError:“ClassOrInterfaceDeclaration”对象没有属性“members”
我甚至不知道从哪里开始修复这个问题。最近我添加了
print self.SYMTAB[self.atr].atr
行,并看到这实际上起了作用。我能想到的唯一一件事是,
FieldDeclaration
没有继承自
TypeDeclaration
,而
members
属性实际上就是在这里定义的。但这有什么关系呢?我正在访问
ClassOrInterfaceDeclaration
节点,它在herit from
TypeDeclaration
?此对象应具有
members
属性。关于如何访问此属性,我缺少什么?

问题 您的程序中似乎存在多个其他问题,但是:

class TypeDeclaration(BodyDeclaration):
    def __init__(self, kwargs={}):
        super(TypeDeclaration, self).__init__(kwargs)
        self.members = map(lambda x: IMPORTS[x[u'@t']](x),
                        kwargs.get(u'members').get(u'@e', []))
该部分:

kwargs.get(u'members')
尝试访问您即将创建的
self.members

您将
u'@t':u'ClassOrInterfaceDeclaration'
放入
d
中。然后在这里:

        self.members = map(lambda x: IMPORTS[x[u'@t']](x),
                        kwargs.get(u'members').get(u'@e', []))
您尝试访问即将创建的
ClassOrInterfaceDeclaration().members
ClassOrInterfaceDeclaration
的实例化调用包含上述代码的
类型声明的
初始化()

解决方案 在尝试访问成员之前,您需要让所有的
\uuuu init\uuu()函数完成。例如,您可以将所有打印移到自己的方法中:

class FieldDeclaration(BodyDeclaration):
    def __init__(self, kwargs={}):
        super(FieldDeclaration, self).__init__(kwargs)

    def meth(self):
        print '*'*10, 'SYMTAB:'
        for k,v in self.SYMTAB.items():
            print k,v
        print '*'*10
        print 'SYMTAB[self.atr]:',self.SYMTAB[self.atr]
        print self.SYMTAB[self.atr].atr
        print self.SYMTAB[self.atr].members


d = {u'@i': 0, u'@r': None, u'@t': u'CompilationUnit', 'types':
     {u'@e':
      [{u'@t': u'ClassOrInterfaceDeclaration', u'@i': 1, u'@r': 0,
        u'members':
        {u'@e':
         [{u'@t': 'FieldDeclaration', u'@i': 2, u'@r': 1}]}}]}}

c = CompilationUnit(d)
print c
c.SYMTAB[2].meth()
输出:

<__main__.CompilationUnit object at 0x104ef9510>
********** SYMTAB:
0 <__main__.CompilationUnit object at 0x104ef9510>
1 <__main__.ClassOrInterfaceDeclaration object at 0x104ef9610>
2 <__main__.FieldDeclaration object at 0x104ef9710>
**********
SYMTAB[self.atr]: <__main__.ClassOrInterfaceDeclaration object at 0x104ef9610>
0
[<__main__.FieldDeclaration object at 0x104ef9710>]

**********符号表:
0
1.
2.
**********
符号表[self.atr]:
0
[]

您能以更紧凑的格式重现错误吗?请参阅?为什么标记为[多重继承]好的,这很复杂…但不是所有的
节点都有
.member
,只有从
类型声明中派生的节点才有。如果在
SYMTAB
中放入其他内容,则会出现问题。打印导致问题的对象类型如何?可以在添加到
SYMTAB
时添加有效类型检查更接近问题。甚至可能只是
assert hasattr(obj,'member')
@chepner好吧,我希望吸引更多的人关注这个问题。技术上不正确。你能详细说明一下吗?什么是“多个其他问题”?为什么
kwargs.get(u'members'))
be访问属性
self.members
kwargs
是传递给构造函数的局部变量。这映射了
kwargs
字典中包含的列表。此外,这不是导致问题的行,
print self.SYMTAB[self.atr].members
是。正如我在上面的评论中所注意到的,这是
ClassOrInterfaceDeclaration
对象,它应该具有
.members
属性。我看到了问题。在访问时没有定义
成员。一个简单的解决方案是只添加一个伪初始化器:
self.\u members=[]
在地图之前。这当然是一种替代方法。但它将打印
[]
而不是
[]