Python - default value in class method and self

前端 未结 2 993
孤城傲影
孤城傲影 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:45

    First of all, the defaults for keywords arguments in methods can't be mutable objects, like list, dict, etc. Here you can read why.

    Secondly, in def make_projection(self, dimension, angle = self.P['angle']) the self variable is still not defined, so you can get self.P only in method's body.

    Try this:

    class Basis(object):
    
      def __init__(self, P=None):
        self.P = P or {'dimension': 1, 'generation':1}
        self.P['angle'] = np.pi/4
    
      def make_projection(self, dimension, angle=None):
        angle = angle if angle is not None else self.P['angle']  # we must compare to None, because angle can be 0.
        return angle*3
    

提交回复
热议问题