Python中的静态类变量-列表和对象 [英] Static class variables in Python -- Lists & Objects

查看:296
本文介绍了Python中的静态类变量-列表和对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python的新手,具有Java的背景知识.我了解Python中静态类变量的概念,但引起我注意的是,列表和对象的工作方式不同于字符串,例如,它们在类的实例之间共享.

I'm new to Python, with more of a Java background. I understand the concept of static class variables in Python, but it's come to my attention that lists and objects don't work the same way a string would, for example - they're shared between instances of a class.

换句话说:

class box ():

    name = ''
    contents = []

    def __init__ (self, name):
        self.name = name

    def store (self, junk):
        self.contents.append(junk)

    def open (self):
        return self.contents

现在,如果我创建两个实例并尝试向其添加内容,则:

Now if I create two instances and try to add things to them:

a = box('Box A')
b = box('Box B')

a.store('apple')
b.store('berry')

print a.open()
print b.open()

输出:

['apple','berry']
['apple','berry']

很明显,它们在box的两个实例之间共享.

It's very clear they're shared between the two instances of box.

现在,我可以通过以下操作解决此问题:

Now I can get around it by doing the following:

def store (self, junk):
    temp = self.contents
    temp.append(junk)
    self.contents = temp

但是,有没有一种更清洁/更传统的方式?有人可以解释为什么会这样吗?

But is there a cleaner/more conventional way? Can someone explain why this happens?

推荐答案

关键字self使它们独立,就好像您说self.name属于box()类的当前实例一样:

The Key word self makes them independent as if you are saying, self.name, belongs to the current instance of box() class:

class box ():

    def __init__ (self, name):
        self.name = name
        self.contents = []

    def store (self, junk):
        self.contents.append(junk)

    def open (self):
        return self.contents

这篇关于Python中的静态类变量-列表和对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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