尝试做类似的事情:
facility = 'LOG_LOCAL7'
syslog.openlog( 'Blah', 0, syslog.facility)
但我明白了:
AttributeError: 'module' object has no attribute 'facility'
我希望能够将设施设置为变量......
旁注;在Python中,实际调用此语句的不同部分是什么?
syslog.openlog( 'Blah', 0, syslog.LOG_LOCAL7)
是类,方法,属性吗?
答案 0 :(得分:0)
您想使用getattr(https://docs.python.org/3/library/functions.html#getattr)
facility = 'LOG_LOCAL7'
syslog.openlog( 'Blah', 0, getattr(syslog, facility))
答案 1 :(得分:0)
要回答第一部分,您需要getattr
:
模块
getattr
中内置函数__builtin__
的帮助:
getattr(...)
getattr(object, name[, default]) -> value
Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y. When a default argument is given, it is returned when the attribute doesn't exist; without it, an exception is raised in that case.
所以,你需要:
syslog.openlog('Blah', 0, getattr(syslog, facility))
关于你的问题的第二部分,关于陈述本身的细分:
syslog
(模块).
(scope resolution operator)openlog
(模块的一个属性,在本例中是一个函数)'Blah'
(函数的参数)