oop - Accessing variable and functions in object oriented python - python -
- how declare default value in python object?
without python object looks fine:
def obj(x={123:'a',456:'b'}): return x fb = obj() print fb
with python object following error:
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'
- how object return value of variable in object?
with python object, got error:
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)
you didn't define class, defined function nested functions.
def foobar(): def __init__(self,x={123:'a',456:'b'}): self.x = x def getstuff(self,field): return x[field]
use class
define class instead:
class foobar: def __init__(self,x={123:'a',456:'b'}): self.x = x def getstuff(self, field): return self.x[field]
note need refer self.x
in getstuff()
.
demo:
>>> 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'}
do note using mutable value function keyword argument default not idea. function arguments defined once, , can lead unexpected errors, classes share same dictionary.
Comments
Post a Comment