6 Replies - 875 Views - Last Post: 02 October 2011 - 09:20 AM Rate Topic: -----

#1 jbedo465  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 24
  • Joined: 18-February 10

How do I initialize a class object with a field?

Posted 01 October 2011 - 01:46 PM

Hi all,

I'm trying to initialize a field to an empty list in the constructor for a class.

This is what I have in the class:
 container = []
 def __init__(self):
        self.container = container



I can't figure out what the correct syntax is here. I will call it later like this:

container.appendToken(triplet)



Also, when I call the constructor for it I have this:

container = myClass()



Am I way off base here? I'm getting this error:

NameError: global name 'container' is not defined

Any ideas here?

Thanks,
JB

This post has been edited by jbedo465: 01 October 2011 - 01:46 PM


Is This A Good Question/Topic? 0
  • +

Replies To: How do I initialize a class object with a field?

#2 Simown  Icon User is offline

  • Blue Sprat
  • member icon

Reputation: 319
  • View blog
  • Posts: 650
  • Joined: 20-May 10

Re: How do I initialize a class object with a field?

Posted 01 October 2011 - 02:51 PM

The way you have done it, an empty container will not be part of every instance of the class, even though it's mostly valid syntax. This is how it should look:

class myClass:
    def __init__(self, container=[]):
             self.container = container

>>> instance = myClass()
>>> instance.container
[]



The container is passed (with a default argument) to the constructer inside the __init__ method, if you wanted the container to contain something else, you could pass that:

>>> anotherInstance = myClass([1, 2, 3])
>>> anotherInstance.container
...
[1, 2, 3]



Or you could just bind the container to an empty list without an argument:

class myClass:
    def __init__(self):
             self.container = []



Hope that helps :)

This post has been edited by Simown: 01 October 2011 - 02:53 PM

Was This Post Helpful? 2
  • +
  • -

#3 jbedo465  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 24
  • Joined: 18-February 10

Re: How do I initialize a class object with a field?

Posted 02 October 2011 - 07:11 AM

Simown,

Thanks, that seems to have cleared that up, but now I'm getting this error:

Traceback (most recent call last):
File "test_scanner.py", line 45, in <module>
container.appendToken(triplet)
TypeError: appendToken() takes exactly 1 argument (2 given)

I don't see how appendToken() is getting two arguments, I'm only passing it one. Here are my two files that might be at fault:

#test_scanner.py
from objects_scanner1.scanner import scan
from objects_scanner1.container import makeScannedObjectContainer
from sys import argv, stdin, stderr, exit

if __name__=='__main__':
    filehandle = None
    # Do this only if this module is executed as the main module.
    if (len(argv) == 2):
        filehandle = open(argv[1], "rU") # portable linefeed handling
    else:
        stderr.write(
            "Invalid usage, test driver takes one mandatory file name." \
            + '\n')
        exit(1)
    container = makeScannedObjectContainer()
    linenum = 0
    done = False
    while (not done):
        try:
            tokenlist = scan(filehandle, linenum)
        except ValueError, message:
            stderr.write("ValueError: " + str(message) + "\n")
            exit(1)
        # print "DEBUG type of tokenlist", type(tokenlist), tokenlist
        for triplet in tokenlist:
            container.appendToken(triplet)
            linenum = triplet[2]
            if (triplet[0] == 'EOF'):
                done = True
    filehandle.close()
    tokenList = container.getTokens()
    for tokenTriplet in tokenList:
        print tokenTriplet



And here is the second:

#container.py
class __TupleContainer__(object):
    def __init__(self, container = []):
        self.container = container
    def appendToken(tokenLexemeLinenumberTriplet): # METHOD in STUDENT code.
        if (type(tokenLexemeLinenumberTriplet) != list
                or len(tokenLexemeLinenumberTriplet) != 3
                or type(tokenLexemeLinenumberTriplet[0]) != str
                or type(tokenLexemeLinenumberTriplet[1]) != str
                or type(tokenLexemeLinenumberTriplet[2]) != int):
            raise ValueError,(                                  \
                "argument to appendToken is not a (token,lexeme,lineNumber) " \
                    "3-tuple: " + str(tokenLexemeLinenumberTriplet))
        # Python nested functions cannot modify the binding of a parameter or
        # variable in an enclosing function, but if that binding refers to a
        # mutable data structure such as a list, they can mutate the mutable
        # data structure.
        container.append(tokenLexemeLinenumberTriplet)

    def getTokens():    # METHOD IN STUDENT CLASS
        return tuple(container) # constructs and returns an immutable copy

def makeScannedObjectContainer():
    container2 = __TupleContainer__()
    return container2



Am I missing something here?
There are other files but they aren't at fault.
The line numbers don't match up because I've cut out the comments. Also, makeScannedObjectContainer() should be a "factory function" to pump out __TupleContainer__ objects, that's why I have it outside the __TupleContainer__ class.


Thanks,
JB

This post has been edited by jbedo465: 02 October 2011 - 07:15 AM

Was This Post Helpful? 0
  • +
  • -

#4 Simown  Icon User is offline

  • Blue Sprat
  • member icon

Reputation: 319
  • View blog
  • Posts: 650
  • Joined: 20-May 10

Re: How do I initialize a class object with a field?

Posted 02 October 2011 - 08:14 AM

Your appendToken method has a single argument:

def appendToken(tokenLexemeLinenumberTriplet): 


You need to specify it's an instance method, with self generally, like you did for the __init__ method, that is methods that are part of each object from the class:

def appendToken(self, tokenLexemeLinenumberTriplet): 


You need to do this for every instance method within the class.

This post has been edited by Simown: 02 October 2011 - 08:16 AM

Was This Post Helpful? 2
  • +
  • -

#5 jbedo465  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 24
  • Joined: 18-February 10

Re: How do I initialize a class object with a field?

Posted 02 October 2011 - 08:55 AM

Simown,

So my defs should look like this?

#container.py
class __TupleContainer__(object):
    def __init__(self, container = []):
        self.container = container
    def appendToken(self, tokenLexemeLinenumberTriplet): # METHOD in STUDENT code.
        if (type(tokenLexemeLinenumberTriplet) != tuple
                or len(tokenLexemeLinenumberTriplet) != 3
                or type(tokenLexemeLinenumberTriplet[0]) != str
                or type(tokenLexemeLinenumberTriplet[1]) != str
                or type(tokenLexemeLinenumberTriplet[2]) != int):
            raise ValueError,(                                  \
                "argument to appendToken is not a (token,lexeme,lineNumber) " \
                    "3-tuple: " + str(tokenLexemeLinenumberTriplet))
        # Python nested functions cannot modify the binding of a parameter or
        # variable in an enclosing function, but if that binding refers to a
        # mutable data structure such as a list, they can mutate the mutable
        # data structure.
        self.container.append(tokenLexemeLinenumberTriplet)

    def getTokens(self):    # METHOD IN STUDENT CLASS
        return tuple(self.container) # constructs and returns an immutable copy

def makeScannedObjectContainer():
    container2 = __TupleContainer__()
    return container2



It works, but is this what it should look like conventionally? I'm very new to python and would like to keep with conventions. Simown, thank you for all the help, I appreciate it.

Thank you,
JB
Was This Post Helpful? 0
  • +
  • -

#6 Simown  Icon User is offline

  • Blue Sprat
  • member icon

Reputation: 319
  • View blog
  • Posts: 650
  • Joined: 20-May 10

Re: How do I initialize a class object with a field?

Posted 02 October 2011 - 09:18 AM

Yes, that's what it should look like conventionally, the self keyword denotes that the object is a single instance of that class. Basically, the method call is referring to itself rather than another instance of the class, or a completely different function.

This post has been edited by Simown: 02 October 2011 - 09:18 AM

Was This Post Helpful? 2
  • +
  • -

#7 jbedo465  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 24
  • Joined: 18-February 10

Re: How do I initialize a class object with a field?

Posted 02 October 2011 - 09:20 AM

Understood,

Thanks again,
JB
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1