在下面的代码中,为什么在类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()
结果:
server1的
1
[ 'attach1']
服务器2
0
[ 'attach1']
答案 0 :(得分:3)
您在类顶部定义的3个变量与类本身相关联,而不是与类的特定实例相关联,因此它们的值在test1和test2之间共享。
如果您打算为classtest
类型的每个对象设置单独的值,那么您应该定义一个构造函数并对每个变量使用'self'前缀:
def __init__(self):
self.smtp_server = ""
self.smtp_port = 0
self.email_attachments = []