- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在 Python 中遇到了一个我不敢相信会发现的问题。见以下代码:
class Container(object):
array = []
def __init__(self):
print self.array
for i in range(0, 5):
container = Container()
container.array.append('Test')
print 'Last Container:', container.array
输出是:
[]
['Test']
['Test', 'Test']
['Test', 'Test', 'Test']
['Test', 'Test', 'Test', 'Test']
Last Container: ['Test', 'Test', 'Test', 'Test', 'Test']
我认为 Container
类在实例化时使用顶部的值进行了初始化。为什么不是这样?
谢谢!
最佳答案
class:
中的代码在创建类时执行,而不是在创建类实例时执行。这是一个更清楚地说明这一点的示例:
>>> class Test(object):
... print "Test"
... def __init__(self):
... print "init"
...
Test
>>> t = Test()
init
请注意,“Test”是在创建类时打印的,而不是在我创建 Test 对象时打印的。
正如其他答案所指出的,如果您希望某个属性对于类的特定实例(而不是类的所有实例)是本地的,则必须将代码放在 __init__
方法:
def __init__(self):
self.array = []
关于python - Python 中的实例变量不像我想象的那样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10970878/
我正在使用 PHP Imagick 来处理图像。 我有两个用例:“调整大小”和“裁剪”。 在“调整大小”中,如果原始图像的尺寸小于给定的宽度和高度,我不希望 Imagick 将其放大,而是希望它简单地
当尝试从 PHP 进行简单的转换时,我收到此错误: exception 'ImagickException' with message 'wand contains no images `Magick
我想了解如何从动画 GIF 中删除帧。 目前我正在尝试这个(作为测试): $count = 1; foreach ($_im AS $frame) { if ($count > 1) { $f
我正在处理 Sylius 1.5 项目,在我的本地环境中一切正常,但是在部署到我的开发环境时,我在过滤图像上遇到错误(使用 liip 想象过滤器)。 该环境由一个运行 sylius 的 docker
我是一名优秀的程序员,十分优秀!