Python可选参数 [英] Python optional parameters

查看:106
本文介绍了Python可选参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

伙计们,我最近才刚开始使用python,并对可选参数感到困惑,说我有这样的程序:

Guys, I just started python recently and get confused with the optional parameters, say I have the program like this:

class B:
   pass

class A:
    def __init__(self, builds = B()):
        self.builds = builds

如果我两次创建A

b = A()
c = A()

并打印他们的版本

print b.builds
print c.builds

我发现他们正在使用完全相同的对象,

I found they are using the exactly same object,

<__main__.B instance at 0x68ee0>
<__main__.B instance at 0x68ee0>

但这不是我想要的,因为如果b更改了某些内部生成状态,则c对象中的一个也会更改.

But it is not what I want, since if b changed some internal state of builds, the one in c object will also be changed.

是否可以通过使用此可选参数语法来每次重新创建此可选参数?

Is it possible to recreate this optional parameters each time by using this optional parameters syntax?

推荐答案

您需要了解默认值是如何工作的,以便有效地使用它们.

You need to understand how default values work in order to use them effectively.

函数是对象.因此,它们具有属性.因此,如果我创建此函数:

Functions are objects. As such, they have attributes. So, if I create this function:

>>> def f(x, y=[]):
        y.append(x)
        return y

我已经创建了一个对象.这是它的属性:

I've created an object. Here are its attributes:

>>> dir(f)
['__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__',   
'__dict__', '__doc__', '__format__', '__get__', '__getattribute__', '__globals__',    
'__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', 
'__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 
'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 
'func_name']

其中之一是func_defaults.听起来很有前途,里面有什么?

One of them is func_defaults. That sounds promising, what's in there?

>>> f.func_defaults
([],)

这是一个包含函数默认值的元组.如果默认值为对象,则元组包含该对象的实例.

That's a tuple that contains the function's default values. If a default value is an object, the tuple contains an instance of that object.

如果您认为f将项目添加到列表中,则返回一些相当违反直觉的行为,如果未提供列表,则返回仅包含该项目的列表:

This leads to some fairly counterintuitive behavior if you're thinking that f adds an item to a list, returning a list containing only that item if no list is provided:

>>> f(1)
[1]
>>> f(2)
[1, 2]

但是,如果您知道默认值是存储在函数属性之一中的对象实例,那么它就不那么直观了:

But if you know that the default value is an object instance that's stored in one of the function's attributes, it's much less counterintuitive:

>>> x = f(3)
>>> y = f(4)
>>> x == y
True
>>> x
[1, 2, 3, 4]
>>> x.append(5)
>>> f(6)
[1, 2, 3, 4, 5, 6]

知道了这一点,很显然,如果您希望函数参数的默认值是新列表(或任何新对象),则不能简单地将对象的实例存储在func_defaults中.每次调用该函数时,您都必须创建一个新的

Knowing this, it's clear that if you want a default value of a function's parameter to be a new list (or any new object), you can't simply stash an instance of the object in func_defaults. You have to create a new one every time the function is called:

>>>def g(x, y=None):
       if y==None:
           y = []
       y.append(x)
       return y

这篇关于Python可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆