社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

Java和Python对静态变量的不同术语?[复制品]

Jonas Grønbek • 6 年前 • 1727 次点击  

我有一个关于赋值时类变量作用域持久性的问题。

我有一个字典作为一个类变量,当我在实例方法中为变量分配另一个字典时,范围似乎会丢失,并且值不再在实例之间持久化。

下面是代码片段:

class MyBaseClass(object):
    my_class_dict = {}  

    def __init__(self):
        print "Keys length: ", len(self.my_class_dict)
        if not len(self.my_class_dict.keys()):
            print "Initializing my_class_dict."
            # VERION  1 
            # self.my_class_dict.update({1:2})
            # VERSION 2 
            # self.my_class_dict = {1:2}
            # VERSION 3             
            self.my_class_dict[1] = 2


class MyChildClass1(MyBaseClass):

    def __init__(self):
        super(MyChildClass1, self).__init__()


class MyChildClass2(MyBaseClass):

    def __init__(self):
        super(MyChildClass2, self).__init__()       

if __name__=='__main__':
    child_1 = MyChildClass1()
    child_2 = MyChildClass2()

    print child_1.my_class_dict
    print child_2.my_class_dict

结果如下。

版本1(1初始化,作用域持久化)

Keys length:  0
Initializing my_class_dict.
Keys length:  1
{1: 2}
{1: 2}

版本2(2次初始化,范围丢失)

Keys length:  0
Initializing my_class_dict.
Keys length:  0
Initializing my_class_dict.
{1: 2}
{1: 2}

版本3(1初始化,作用域持久化)

密钥长度:0
正在初始化我的类。
按键长度:1
{1:2 }
{1:2 }

因此,看起来作用域只在完全对象分配时丢失。为什么会这样?这样做的理由是什么?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/43796
 
1727 次点击  
文章 [ 1 ]  |  最新文章 6 年前