在面向对象python中访问变量和函数 如何在python对象中声明默认值?
如果没有python对象,它看起来很好:在面向对象python中访问变量和函数 如何在python对象中声明默认值?,python,oop,variables,init,Python,Oop,Variables,Init,如果没有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()
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'
def foobar():
def uu init uuu(self,x={123:'a',456:'b'}):
self.x=x
def getStuff(自我,字段):
返回x[字段]
fb=foobar()
打印fb.x
回溯(最近一次呼叫最后一次):
文件“testclass.py”,第9行,在
打印fb.x
AttributeError:“非类型”对象没有属性“x”
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)
def foobar():
def uu init uuu(self,x={123:'a',456:'b'}):
self.x=x
def getStuff(自我,字段):
返回x[字段]
fb2=foobar({678:'c'})
打印fb2.getStuff(678)
回溯(最近一次呼叫最后一次):
文件“testclass.py”,第8行,在
fb2=foobar({678:'c'})
TypeError:foobar()不接受任何参数(给定1个)
您没有定义类,而是定义了具有嵌套函数的函数
def foobar():
def __init__(self,x={123:'a',456:'b'}):
self.x = x
def getStuff(self,field):
return x[field]
使用class
来定义类:
class foobar:
def __init__(self,x={123:'a',456:'b'}):
self.x = x
def getStuff(self, field):
return self.x[field]
请注意,您需要在getStuff()
中参考self.x
演示:
请注意,对函数关键字参数默认值使用可变值通常不是一个好主意。函数参数只定义一次,可能会导致意外错误,因为现在所有类共享同一个字典
请参阅。要在python中定义类,必须使用
class classname(parentclass):
def __init__():
<insert code>
类类名称(父类):
def u u init__;()
在代码中,您声明的是一个方法,而不是一个类
class foobar:
而不是
def foobar():
值得指出的是可变默认参数问题。Martijn打字速度很快!:D
def foobar():