__init__ python类的方法

Sta*_*ess 0 python attributes initialization class

我有一个名为settings的python类,其中包含一个__init__设置如下值的方法:

class settings:
    global appkey
    global appversion
    def __init__(self):
        appkey = 1
        appversion = 1
        applicationname = "app1"
        applicationfile = "app.txt"
Run Code Online (Sandbox Code Playgroud)

在另一个python文件(主脚本)中,我通过以下代码定义了我的设置类的实例:

import settings
from settings import settings
set = settings()
print set.appversion
print set.appkey
print set.applicationfile
Run Code Online (Sandbox Code Playgroud)

但是当我运行我的主要python脚本时,我收到了这个错误:

AttributeError: settings instance has no attribute 'appversion'
Run Code Online (Sandbox Code Playgroud)

我希望当我在这里定义一个类的实例,设置类时,它的init函数将被触发,我将拥有其属性的值.

Mos*_*oye 6

变量是__init__您班级的本地变量.要将它们作为实例属性,您需要使用对实例的点引用将它们绑定到实例:

def __init__(self):
    self.appkey = 1
    ...
Run Code Online (Sandbox Code Playgroud)

使用以下命令将属性绑定到/设置属性的同义(但不那么详细)setattr:

def __init__(self):
    setattr(self, 'appkey', 1)
    ...
Run Code Online (Sandbox Code Playgroud)

另一方面,您不需要该global语句,因为您只想在实例上设置新属性; 与全局命名空间无关.

__init__通过分析字节码,您可以轻松地检查新行为与以前的行为不同:

from dis import dis

class Settings(object):
   def __init__(self):
       self.appkey = 1  

dis(Settings.__init__)
Run Code Online (Sandbox Code Playgroud)
3           0 LOAD_CONST               1 (1)
            2 LOAD_FAST                0 (self)
            4 STORE_ATTR               0 (appkey)
            6 LOAD_CONST               0 (None)
            8 RETURN_VALUE
Run Code Online (Sandbox Code Playgroud)

请注意我们如何调用流行音乐 STORE_FAST,而不是使用vanilla作业STORE_ATTR.