1 import sys
2
3 class dummy(object):
4 def __init__(self, val):
5 self.val = val
6
7 class myobj(object):
8 def __init__(self, resources):
9 self._resources = resources
10
11 class ext(myobj):
12 def __init__(self, resources=[]):
13 #myobj.__init__(self, resources)
14 self._resources = resources
15
16 one = ext()
17 one._resources.append(1)
18 two = ext()
19
20 print one._resources
21 print two._resources
22
23 sys.exit(0)
Run Code Online (Sandbox Code Playgroud)
这将打印的参考对象分配one._resources
两个one
和two
对象.我认为这two
将是一个空数组,因为如果在创建对象时没有定义它,它就会明确地设置它.取消注释也会myobj.__init__(self, resources)
做同样的事情.使用super(ext, self).__init__(resources)
也做同样的事情.
我可以使用它的唯一方法是使用以下方法:
two = ext(dummy(2))
Run Code Online (Sandbox Code Playgroud)
我不必在创建对象时手动设置默认值以使其工作.或者我也许.有什么想法吗?
我尝试使用Python 2.5和2.6.
你应该改变
def __init__(self, resources=[]):
self._resources = resources
Run Code Online (Sandbox Code Playgroud)
至
def __init__(self, resources=None):
if resources is None:
resources = []
self._resources = resources
Run Code Online (Sandbox Code Playgroud)
一切都会好起来的.这是默认参数处理方式的细节,如果它们是可变的.本页的讨论部分提供了更多信息.
归档时间: |
|
查看次数: |
242 次 |
最近记录: |