![](/img/trans.png)
[英]Python: can function be defined inside of another function's argument list?
[英]using an object passed as a function argument (function is defined inside another class)
我正在尝试访问传递给我的函数的对象(在类内部定义)。
publish_alert
类中定义的AlertPublishInterface
。 publish_alert
一个称为类的实例AlertVO
publish_alert
接收到此传递的参数实例,我就只是尝试在AlertPublishInterface
类(定义了称为publish_alert
函数的类)内访问传递的参数实例的数据成员。 在步骤2中,即在访问传递的参数实例的成员时,我得到AttributeError
:
AttributeError:AlertPublishInterface实例没有属性“ alert_name”
这是代码片段:
AlertPublishInterface文件:
import datetime
import logging.config
import django_model_importer
logging.config.fileConfig('logging.conf')
logger = logging.getLogger('alert_publish_interface')
from alert.models import AlertRule #Database table objects defined in the model file
from alert.models import AlertType #Database table objects defined in the model file
import AlertVO #This is instance whose members am trying to simple access below...!
class AlertPublishInterface:
def publish_alert(o_alert_vo, dummy_remove):
print o_alert_vo.alert_name #-----1----#
alerttype_id = AlertType.objects.filter(o_alert_vo.alert_name,
o_alert_vo.alert_category, active_exact=1) #-----2----#
return
AlertVO定义为:
class AlertVO:
def __init__(self, alert_name, alert_category, notes,
monitor_item_id, monitor_item_type, payload):
self.alert_name = alert_name
self.alert_category = alert_category
self.notes = notes
self.monitor_item_id = monitor_item_id
self.monitor_item_type = monitor_item_type
self.payload = payload
调用代码段(调用AlertPublishInterface
的publish_alert
函数):
from AlertVO import AlertVO
from AlertPublishInterface import AlertPublishInterface;
o_alert_vo = AlertVO(alert_name='BATCH_SLA', alert_category='B',
notes="some notes", monitor_item_id=2, monitor_item_type='B',
payload='actual=2, expected=1')
print o_alert_vo.alert_name
print o_alert_vo.alert_category
print o_alert_vo.notes
print o_alert_vo.payload
alert_publish_i = AlertPublishInterface()
alert_publish_i.publish_alert(o_alert_vo)
但是,它在上面标记有错误的#----- 1 ----#和#----- 2 ---#行失败,似乎是将AlertVO
对象( o_alert_vo
实例)与AlertPublishInterface
类相关联:
运行时完整的屏幕输出块:
python test_publisher.py In test_publisher BATCH_SLA B some notes actual=2, expected=1 Traceback (most recent call last): File "test_publisher.py", line 17, in alert_publish_i.publish_alert(o_alert_vo.alert_name) File "/home/achmon/data_process/AlertPublishInterface.py", line 26, in publish_alert print o_alert_vo.alert_name AttributeError: AlertPublishInterface instance has no attribute 'alert_name'
经过大量搜索后无法摆脱上述错误...有人可以帮忙...吗?
谢谢...!(也很紧急...!)
出现此错误的原因是,第一个参数是类本身。 通常,这称为自我。
我也可以将其标识为django(在这种情况下,如果不是从其他django类继承,则还应该从object继承,以使其成为新的样式类)
无论如何,只要将self作为您在publish_ alert中的第一个参数,它可能会停止抛出该错误。
def publish_alert(o_alert_vo, dummy_remove):
应该是def publish_alert(self, o_alert_vo, dummy_remove):
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.