在 Python 中声明实例变量的两种方法?

Roh*_*han 3 python instance-variables

两者之间的功能和幕后发生的事情有什么不同吗?

class Class:
    def __init__(self, var1):
        self.var1 = var1
Run Code Online (Sandbox Code Playgroud)

class Class:
    var1 = ""
    def __init__(self, var1):
        self.var1 = var1
Run Code Online (Sandbox Code Playgroud)

在 Python 中?

Mik*_*ler 10

让我们来探索一下。这是你的课:

class Class:
    var1 = 'in class'
    def __init__(self, var1):
        self.var1 = var1

c = Class('in inst')
Run Code Online (Sandbox Code Playgroud)

访问c.var1显示var1来自实例的:

>>> c.var1
'in inst'
Run Code Online (Sandbox Code Playgroud)

它位于里面__dict__c

>>> c.__dict__
{'var1': 'in inst'}
Run Code Online (Sandbox Code Playgroud)

类变量var1是在 __dict__Class

>>> Class.__dict__['var1']
'in class'
Run Code Online (Sandbox Code Playgroud)

现在创建一个只有一个类变量的类:

class Class2:
    var1 = 'in class'

c2 = Class2()
Run Code Online (Sandbox Code Playgroud)

由于实例中没有任何内容,因此var1将使用来自类:

>>> c2.var1
'in class'
Run Code Online (Sandbox Code Playgroud)

__dict__c2是空的:

>>> c2.__dict__
{}
Run Code Online (Sandbox Code Playgroud)

Python 总是var1先在实例中查找,然后再返回到类。


Dai*_*arf 5

正如我在评论中指出的,Class.var1 是一个共享变量。如果您不使用 __init__ 中的非共享变量删除它,则每个实例都可以将其作为 self.var1 进行访问。以下是所发生情况的示例:

class Test(object):
    shared = 0
    def __init__(self, i):
        self.notshared = i
    def intro(self):
        print("Shared is " + str(self.shared))
        print("NotShared is " + str(self.notshared))

test1 = Test(4)

test1.intro()
# Shared is 0
# NotShared is 4

Test.shared = 5
test1.intro()
# Shared is 5
# NotShared is 4

test2 = Test(3)
test2.intro()
# Shared is 5
# NotShared is 3
Run Code Online (Sandbox Code Playgroud)

但请注意,如果您self.shared随后写入变量,则无法self.shared再使用以下方式访问共享变量:

test1.shared = 12
test1.intro()
# Shared is 12
# NotShared is 4
test2.intro()
# Shared is 5
# NotShared is 3
Run Code Online (Sandbox Code Playgroud)