0
  1. How to I declare a default value in a python object?

Without a python object it looks fine:

def obj(x={123:'a',456:'b'}):
    return x
fb = obj()
print fb

With a python object I get the 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'
  1. How do I get the object to return the value of a variable in the object?

With a python object, I got an 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)
alvas
  • 115,346
  • 109
  • 446
  • 738
  • [Don't use mutable default arguments.](http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument) – Ashwini Chaudhary Sep 04 '13 at 09:46

3 Answers3

5

You didn't define a class, you defined a function with nested functions.

def foobar():
    def __init__(self,x={123:'a',456:'b'}):
        self.x = x
    def getStuff(self,field):
        return x[field]

Use class to define a class instead:

class foobar:
    def __init__(self,x={123:'a',456:'b'}):
        self.x = x
    def getStuff(self, field):
        return self.x[field]

Note that you need to refer to 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 that using a mutable value for a function keyword argument default is generally not a good idea. Function arguments are defined once, and can lead to unexpected errors, as now all your classes share the same dictionary.

See "Least Astonishment" and the Mutable Default Argument.

Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

to define a class in python you have to use

    class classname(parentclass):
        def __init__():
            <insert code>

With your code you're declaring a method not a class

user1628311
  • 166
  • 1
  • 3
  • 12
1

Use

class foobar:

instead of

def foobar():
Michel Keijzers
  • 15,025
  • 28
  • 93
  • 119