蟒蛇。奇怪的类属性行为 [英] Python. Strange class attributes behavior

查看:148
本文介绍了蟒蛇。奇怪的类属性行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

>>> class Abcd:

...     a = ''
...     menu = ['a', 'b', 'c']
... 
>>> a = Abcd()
>>> b = Abcd()
>>> a.a = 'a'
>>> b.a = 'b'
>>> a.a
'a'
>>> b.a
'b'

这是正确的,每个对象都有自己的'a' ...

It's all correct and each object has own 'a', but...

>>> a.menu.pop()
'c'
>>> a.menu
['a', 'b']
>>> b.menu
['a', 'b']


如何使用列表作为类属性?

How could this happen? And how to use list as class attribute?

推荐答案

这是因为你初始化< c $ c> menu 属性将所有实例设置为指向同一列表,而不是具有相同值的不同列表。

This is because the way you're initializing the menu property is setting all of the instances to point to the same list, as opposed to different lists with the same value.

而是使用类的 __ init __ 成员函数来初始化值,从而创建一个新列表并将该列表分配给该类的特定实例的属性:

Instead, use the __init__ member function of the class to initialize values, thus creating a new list and assigning that list to the property for that particular instance of the class:

class Abcd:
    def __init__(self):
        self.a = ''
        self.menu = ['a', 'b', 'c']

这篇关于蟒蛇。奇怪的类属性行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆