Python - default value in class method and self

前端 未结 2 992
孤城傲影
孤城傲影 2021-01-23 03:48

I have the following class and method:

class Basis(object):

 def __init__(self, P = {\'dimension\': 1, \'generation\':1}):

  self.P = P
  self.P[\'angle\'] = n         


        
2条回答
  •  南方客
    南方客 (楼主)
    2021-01-23 04:30

    Python default values for arguments are evaluated when the function is defined, not when the function is called.

    You need to do something like:

    def foo(self, x, y=None):
        if y is None:
            y = self.defval
    

    This is also the reason for which having a mutable default (e.g. a dictionary) is a dangerous trap in Python; if you change the value that was given by default you're also changing what will be the default in future calls.

提交回复
热议问题