0

In the following code, why does setting the email_attachments list to 'attach1' in class test1 also set the email_attachments list in class test2 to 'attach1'?

Class:

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

Script:

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()

results:

server1

1

['attach1']

server2

0

['attach1']

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343

1 Answers1

3

The 3 variables you have defined at the top of the class are associated with the class itself, not with a particular instance of the class, so their values are shared between test1 and test2.

If your intention is to have separate values for each object of type classtest then you should define a constructor and use the 'self' prefix with each variable:

def __init__(self):
    self.smtp_server = ""
    self.smtp_port = 0
    self.email_attachments = []
codebox
  • 19,927
  • 9
  • 63
  • 81