我有一个名为 settings 的 python 类,它包括一个__init__
用于设置一些值的方法,如下所示:
class settings:
global appkey
global appversion
def __init__(self):
appkey = 1
appversion = 1
applicationname = "app1"
applicationfile = "app.txt"
在另一个 python 文件(主脚本)中,我通过以下代码定义了我的设置类的一个实例:
import settings
from settings import settings
set = settings()
print set.appversion
print set.appkey
print set.applicationfile
但是当我运行我的主要 python 脚本时,我收到了这个错误:
AttributeError: settings instance has no attribute 'appversion'
我希望当我定义一个类的实例时,这里的设置类,它的init函数将被触发,我将拥有它的属性值。
变量是__init__
您的类的局部变量。要将它们作为实例属性,您需要使用对实例的点引用将它们绑定到实例:
def __init__(self):
self.appkey = 1
...
使用以下命令将属性绑定到实例上的/设置属性的同义词(但不那么冗长)setattr
:
def __init__(self):
setattr(self, 'appkey', 1)
...
另一方面,您不需要该global
语句,因为您只想在实例上设置新属性;与全局命名空间无关。
您可以__init__
通过分析字节码轻松检查新的行为与以前的不同:
from dis import dis
class Settings(object):
def __init__(self):
self.appkey = 1
dis(Settings.__init__)
3 0 LOAD_CONST 1 (1)
2 LOAD_FAST 0 (self)
4 STORE_ATTR 0 (appkey)
6 LOAD_CONST 0 (None)
8 RETURN_VALUE
请注意,我们不像普通 STORE_FAST
赋值那样调用流行,而是调用STORE_ATTR
.
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句