- 如何在 python 对象中声明默认值?
如果没有 python 对象,它看起来很好:
def obj(x={123:'a',456:'b'}):
return x
fb = obj()
print fb
使用 python 对象,我收到以下错误:
def foobar():
def __init__(self,x={123:'a',456:'b'}):
self.x = x
def getStuff(self,field):
return x[field]
fb = foobar()
print fb.x
Traceback (most recent call last):
File "testclass.py", line 9, in <module>
print fb.x
AttributeError: 'NoneType' object has no attribute 'x'
- 如何让对象返回对象中变量的值?
使用 python 对象,我得到一个错误:
def foobar():
def __init__(self,x={123:'a',456:'b'}):
self.x = x
def getStuff(self,field):
return x[field]
fb2 = foobar({678:'c'})
print fb2.getStuff(678)
Traceback (most recent call last):
File "testclass.py", line 8, in <module>
fb2 = foobar({678:'c'})
TypeError: foobar() takes no arguments (1 given)