Python optional parameters -


Friends, I recently started Python and confused with alternative parameters, I have a program like this:

  class B: pass class A: df __int __ (self, build = b ()): self. Builds = Build builds  

If I have once twice

  b = a () c = a ()  

and print your build

  print b.builds print c.builds  

I found that they are using the same thing, < / P>

  & lt; __ Main __. B example 0x68ee0 & gt; & Lt; __ Main __. B example on 0x68ee0 & gt;  

But this is not my wish, because if b has changed some internal state of the build, then in the c object too One will

You need to understand how the default values ​​work to use their methodology

Function objects are such that they have properties, so if I make this function:

  gt;> Def f (x, y = [] ): Y.append (x) returns y  

I have an ob Here are the features of this:

  & gt; & gt; & gt; Dir (f) ['__call__', '__class__', '__closure__', '__code__', '__defaults__ ',' __dict__ ',' __dict__ ',' __doc__ ',' __format__ ',' __get__ ',' __getattribute__ ',' __globals__ ',' __hit__ ',' __mitt__ ',' __module__ ',' __name__ ',' __new__ ' '__reuce_', '__recre_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__ subclasshook__', 'func_closure', 'func_code', 'func_defaults',' func_dict ',' func_doc ',' Func_globals', 'func_name']  

One of them is func_defults . It looks promising, what is there?

  & gt; & Gt; & Gt; F.func_defaults ([],) This is a tupal in which the default value of the function is included. If a default value is an object, then there is an example of that object in the tube.  

If you are thinking that a list is not available, then adding item to an item in a list to return that item to a list, Some tend to consider fairly reputable behavior:

  & gt; & Gt; & Gt; F (1) [1] & gt; & Gt; & Gt; F (2) [1, 2]  

But if you know that the default value is an object instance that is stored in the properties of a function, then this is a very minimal contradiction:

  & gt; & Gt; & Gt; X = f (3)> gt; & Gt; & Gt; Y = f (4)> gt; & Gt; & Gt; X == y true & gt; & Gt; & Gt; X [1, 2, 3, 4] & gt; & Gt; & Gt; X.append (5) & gt; & Gt; & Gt; To know this, it is clear that if you want a default value of the parameters of a function, then create a new list (6) [1, 2, 3, 4, 5, 6]  

or any new object), you can not just hide an example of an object in func_defaults . You are called a function every time:

  & Gt; & Gt; DRF G (X, Y = None): If y == none: y = [] Y.append (x) returns  

Comments

Popular posts from this blog

asp.net - Javascript/DOM Why is does my form not support submit()? -

sockets - Delphi: TTcpServer, connection reset when reading -

javascript - Classic ASP "ExecuteGlobal" statement acting differently on two servers -