简体   繁体   中英

Creating a class the have a “list creation” method and an “append to the list” method?

I am trying to create a class that can handle a string-to-list conversion and also is capable of adding to the created list. However I am not sure how to do that. If I provide the class with an already prepared list and have an "append" function, everything works fine:

class EnvObj(object):

    def __init__(self, envVariable):
        self.envVariable = envVariable

    def appendElement(self, newElement):
        self.envVariable.append(newElement)

    def listElements(self):
        return self.envVariable

initList=['APPLE', 'CAR', 'HOUSE', 'PEN', 'CAT']
myEnvObj = EnvObj(initList)

print "Initial List:"
print myEnvObj.listElements()
print "Adding a new element"
myEnvObj.appendElement('BANANA')
print "A new listElements() request:"
print myEnvObj.listElements()
print "Adding a new element"
myEnvObj.appendElement('MILK')
print "A new listElements() request:"
print myEnvObj.listElements()

So this works, after each appendElement() stage, I can see the list growing just fine. However, when I try to create a method for creating the list and then handle the append, everything starts to fall apart.

envVariableList = []
class EnvObj(object):

    def __init__(self, envVariable):
        self.envVariable = envVariable

    def elementList(self):
        envVariableList = self.envVariable.split(":")
        return envVariableList

    def appendElement(self, newElement):
        envVariableList.append(newElement)

    def listElements(self):
        return self.elementList()

tmpString="APPLE:CAR:HOUSE:PEN:CAT"
myEnvObj = EnvObj(tmpString)
myEnvObj.elementList()

print "Initial List:"
print myEnvObj.listElements()
print "Adding a new element"
myEnvObj.appendElement('BANANA')
print "A new listElements() request:"
print myEnvObj.listElements()
print "Adding a new element"
myEnvObj.appendElement('MILK')
print "A new listElements() request:"
print myEnvObj.listElements()

In that second case, I cannot see the list actually being appended to. Apologies for the messy code, but I hope that I was able to illustrate the idea. I am sure that it has to with the fact that something is getting reset or lost every time the instance is created.

Thanks.

You missed the self in your methods :

def elementList(self): self.envVariableList = self.envVariable.split(":") return envVariableList

def appendElement(self, newElement): self.envVariableList.append(newElement)

What you did is just making a new variable and return it when you call myEnvObj.elementList() . It didn't instantiate it in the object 1 . By using self.myvar = [...] it solve your issue

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM