[英]Accessing variable and functions in object oriented python - 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)
您没有定义类,而是定义了带有嵌套函数的函数。
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]
请注意,您需要参考self.x
在getStuff()
演示:
>>> class foobar:
... def __init__(self,x={123:'a',456:'b'}):
... self.x = x
... def getStuff(self, field):
... return self.x[field]
...
>>> fb = foobar()
>>> print fb.x
{456: 'b', 123: 'a'}
请注意,对于函数关键字参数default使用可变值通常不是一个好主意。 函数参数定义一次 ,并且可能导致意外错误,因为现在所有类都共享同一字典。
请参见“最少惊讶”和可变默认参数 。
在python中定义一个类,你必须使用
class classname(parentclass):
def __init__():
<insert code>
使用您的代码,您声明的是方法而不是类
采用
class foobar:
代替
def foobar():
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.