AttributeError:'module'对象没有属性'something'

时间:2015-03-11 05:11:11

标签: python oop python-2.7

尝试做类似的事情:

facility = 'LOG_LOCAL7'
syslog.openlog( 'Blah', 0, syslog.facility)

但我明白了:

 AttributeError: 'module' object has no attribute 'facility'

我希望能够将设施设置为变量......

旁注;在Python中,实际调用此语句的不同部分是什么?

syslog.openlog( 'Blah', 0, syslog.LOG_LOCAL7)
  • 系统日志
  • openlog
  • '布拉赫'

是类,方法,属性吗?

2 个答案:

答案 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'(函数的参数)