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)
1

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Worth pointing out the mutable default argument issue as well.
Martijn is a fast typist! :D
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

Comments

1

Use

class foobar:

instead of

def foobar():

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.