gpt4 book ai didi

Python继承导致非法属性错误

转载 作者:太空宇宙 更新时间:2023-11-03 10:48:11 24 4
gpt4 key购买 nike

我有下面一个类 vuln.py

from reportlab.graphics.shapes import Drawing, String, Rect

class vuln(Drawing):
def __init__(self, width=300, height=150, report_type=None, *args, **kw):
Drawing.__init__(self, width, height, *args, **kw)
self.report_type = report_type

def print_report(self):
print self.report_type

并调用程序rep.py

import vuln

obj = vuln.vuln(report_type="abc")
obj.print_report()

执行后报错,

Traceback (most recent call last):
File "rep.py", line 3, in <module>
obj = vuln.vuln(report_type="abc")
File "/data/support/vuln.py", line 5, in __init__
self.report_type = report_type
File "/usr/lib64/python2.6/site-packages/reportlab/graphics/shapes.py", line 359, in __setattr__
validateSetattr(self,attr,value) #from reportlab.lib.attrmap
File "/usr/lib64/python2.6/site-packages/reportlab/lib/attrmap.py", line 118, in validateSetattr
raise AttributeError, "Illegal attribute '%s' in class %s" % (name, obj.__class__.__name__)
AttributeError: Illegal attribute 'report_type' in class vuln

请帮忙知道是什么错误。

最佳答案

长话短说,他们的开发人员正在给您带来这种痛苦,并在做他们不应该在 Python 中做的事情。幸运的是它是开源的。您正在使用的 API 动态检查从 Shape 继承的类的属性,或者如他们在 /reportlab/graphics/shapes.py, line 359 中所说:

if shapeChecking:
"""This adds the ability to check every attribute assignment as it is made.
It slows down shapes but is a big help when developing. It does not
get defined if rl_config.shapeChecking = 0"""
def __setattr__(self, attr, value):
"""By default we verify. This could be off
in some parallel base classes."""
validateSetattr(self,attr,value) #from reportlab.lib.attrmap

继续挖掘代码和 attrmap source code 的第 99 行您可以看到导致问题的原因:

def validateSetattr(obj,name,value):
'''validate setattr(obj,name,value)'''
if rl_config.shapeChecking:
map = obj._attrMap
if map and name[0]!= '_':
#we always allow the inherited values; they cannot
#be checked until draw time.
if isinstance(value, DerivedValue):
#let it through
pass
else:
try:
validate = map[name].validate
if not validate(value):
raise AttributeError("Illegal assignment of '%s' to '%s' in class %s" % (value, name, obj.__class__.__name__))
except KeyError:
raise AttributeError("Illegal attribute '%s' in class %s" % (name, obj.__class__.__name__))
obj.__dict__[name] = value

请注意,他们不检查以 ___ 开头的属性,pythonists 使用这些属性来指示“私有(private)”变量;因此,您可以按如下方式修复您的代码:

from reportlab.graphics.shapes import Drawing, String, Rect

class vuln(Drawing):
def __init__(self, width=300, height=150, report_type=None, *args, **kw):
Drawing.__init__(self, width, height, *args, **kw)
self._report_type = report_type

def print_report(self):
print self._report_type

然后一切都应该正常工作。

关于Python继承导致非法属性错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57170458/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com