【问题标题】:When are static variables initialized in Python?Python中的静态变量什么时候初始化?
【发布时间】:2019-09-22 19:15:33
【问题描述】:

考虑下面的代码

class Foo:
    i = 1 # initialization
    def __init__(self):
        self.i += 1

t = Foo()
print(t.i)

i的初始化究竟是什么时候发生的? 在执行init方法之前还是之后

【问题讨论】:

  • 这是一个类属性,它是在类的时候定义的。您可以在实例化之前访问Foo.i
  • 查看 Foo.i 与 t.i 可能会有所帮助:ideone.com/NPWMSX

标签: python python-3.x oop


【解决方案1】:

之前。

__init__ 方法在 Foo 实例化之前不会运行。只要在代码中遇到类定义,就会运行i=1

您可以通过添加打印语句来查看:

print('Before Foo')
class Foo:
    i = 1
    print(f'Foo.i is now {i}')
    
    def __init__(self):
        print('Inside __init__')
        self.i += 1
        print(f'i is now {self.i}')
print('After Foo')

print('Before __init__')
foo = Foo()
print('After __init__')

哪个打印:

Before Foo
Foo.i is now 1
After Foo
Before __init__
Inside __init__
i is now 2
After __init__

但请注意,您的 self.i += 1 不会修改类属性 Foo.i

foo.i # This is 2
Foo.i # This is 1

【讨论】:

  • i = 1 在本地范围内运行,但 i += 1 只会引发错误
  • @MadPhysicist 他加了self,所以这不是错误。
  • 感谢有关未命名函数 (f'') 的提示。非常喜欢。
  • @Dan 这就是通常所说的 f-strings。它用于字符串格式化。 python.org/dev/peps/pep-0498
【解决方案2】:

class 属性在你第一次在源代码中使用 ClassName 时被初始化,你也可以通过 ClassMethod.attribute 来使用代码中的 class 属性

class Foo:
    i = 1 # initialization
    def __init__(self):
        #Use ClassName.attribute to access class attribute
        Foo.i += 1

#I used the Name of the class here, Foo.i will be 1
print(Foo.i)
#1

#Instantiated Foo
t = Foo()

#Value of i changes to 2
print(t.i)
#2

【讨论】:

  • 嗨@chepner,感谢您的编辑,但应该改为static class attribute 吗?
  • 不,Python 中唯一名称中带有“static”的就是静态方法。
  • 是的,一个类方法或一个属性天生就是static
  • 在 Python 中定义“静态”。
  • 那是我没有答案@chepner 你能解释一下或提供一个例子吗:)
猜你喜欢
  • 2012-02-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
  • 2012-03-10
  • 1970-01-01
  • 2011-03-30
相关资源
最近更新 更多