通过方法定义中的参数默认值引用同一对象的不同类实例的成员

2024-10-01 04:47:15 发布

您现在位置:Python中文网/ 问答频道 /正文

Python文档介绍了关键字参数(词汇表):

...The variable name designates the local name in the function to which the value is assigned...

因此,我认为一个类的不同实例是完全不同的,除非另有说明 明确地。但是下面的代码引用了两个实例的一个成员变量 通过给定的默认值(好像 方法的关键字字典是一个类变量(“static”))。一旦有人修改了 会员:一切都很好,但如果因为某种原因没有发生:

  1. 我想知道是否有一个很好的理由让代码像它那样运行, 因为这根本不是我所期望的(请参阅代码和输出中的标记)和
  2. 是否有解决问题的好方法(除了使用“copy”之外)。 谢谢。你知道吗

    class C:
        def setParams(self):
            self.e = []
        def setParamsKw(self, kw=['default list']): # <----- kw arg.
            self.eKw = kw                           # <--- that member should
                                                    #      default to the
                                                    #      default argument
                                                    #      (use 'kw.copy()'?)
    
    def outputMember():
        print " c1.e=", c1.e
        print " c2.e=", c2.e
        print " type(c1.e)=", type(c1.e)
        print " type(c2.e)=", type(c2.e)
        print " c1.e == c2.e:", c1.e == c2.e
        print " c1.e is c2.e:", c1.e is c2.e
    
    def outputMemberKw():
        print " c1.eKw=", c1.eKw
        print " c2.eKw=", c2.eKw
        print " type(c1.eKw)=", type(c1.eKw)
        print " type(c2.eKw)=", type(c2.eKw)
        print " c1.eKw == c2.eKw:", c1.eKw == c2.eKw
        print " c1.eKw is c2.eKw:", c1.eKw is c2.eKw # <----- this result
                                                     #      is unexpected
    
    
    c1 = C()
    c2 = C()
    
    print " c1 == c2:",  c1 == c2
    print " c1 is c2:",  c1 is c2
    
    print "Calling setParams for both instances:"
    c1.setParams()
    c2.setParams()
    outputMember()
    
    print "Calling setParamsKw for both instances:"
    c1.setParamsKw()
    c2.setParamsKw()
    outputMemberKw()
    
    print "Now manually modifying members of c1:"
    c1.e = [1, 2, 3, 4, 5]
    c1.eKw = [1, 2, 3, 4, 5]
    print "e:"
    outputMember()
    print "eKw:"
    outputMemberKw()
    

输出:

c1 == c2: False
 c1 is c2: False
Calling setParams for both instances:
 c1.e= []
 c2.e= []
 type(c1.e)= <type 'list'>
 type(c2.e)= <type 'list'>
 c1.e == c2.e: True
 c1.e is c2.e: False
Calling setParamsKw for both instances:
 c1.eKw= ['default list']
 c2.eKw= ['default list']
 type(c1.eKw)= <type 'list'>
 type(c2.eKw)= <type 'list'>
 c1.eKw == c2.eKw: True
 c1.eKw is c2.eKw: True
Now manually modifying members of c1:
e:
 c1.e= [1, 2, 3, 4, 5]
 c2.e= []
 type(c1.e)= <type 'list'>
 type(c2.e)= <type 'list'>
 c1.e == c2.e: False
 c1.e is c2.e: False
eKw:
 c1.eKw= [1, 2, 3, 4, 5]
 c2.eKw= ['default list']
 type(c1.eKw)= <type 'list'>
 type(c2.eKw)= <type 'list'>
 c1.eKw == c2.eKw: False
 c1.eKw is c2.eKw: False

Tags: theselffalsedefaultisdeftypelist