【问题标题】:Why does setting a python 2.7 list cross class boundaries [duplicate]为什么设置python 2.7列表跨越类边界[重复]
【发布时间】:2013-02-26 19:32:45
【问题描述】:

在下面的代码中,为什么将 test1 类中的 email_attachments 列表设置为 'attach1' 也会将 test2 类中的 email_attachments 列表设置为 'attach1'?

类:

class classtest:
    smtp_server = ""
    smtp_port = 0
    email_attachments = []

    def class_print(self):

        print self.smtp_server
        print self.smtp_port
        print self.email_attachments

脚本:

import ClassTest

def main():
    test1 = ClassTest.classtest()
    test1.smtp_server = "server1"
    test1.smtp_port = "1"
    test1.email_attachments.append("attach1")
    test1.class_print()

    print

    test2 = ClassTest.classtest()
    test2.smtp_server = "server2"
    test2.class_print()

main()

结果:

服务器1

1

['attach1']

服务器2

0

['attach1']

【问题讨论】:

    标签: python list class python-2.7


    【解决方案1】:

    您在类顶部定义的 3 个变量与类本身相关联,而不是与类的特定实例相关联,因此它们的值在 test1 和 test2 之间共享。

    如果您的意图是为classtest 类型的每个对象设置单独的值,那么您应该定义一个构造函数并为每个变量使用“self”前缀:

    def __init__(self):
        self.smtp_server = ""
        self.smtp_port = 0
        self.email_attachments = []
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-15
      • 2015-08-22
      • 1970-01-01
      • 1970-01-01
      • 2021-04-16
      • 1970-01-01
      • 2013-07-13
      • 2018-09-11
      相关资源
      最近更新 更多