Home > database >  Class that holds variables and has methods?
Class that holds variables and has methods?

Time:11-23

I have a class like this:

class ErrorMessages(object): 
    """a class that holds all error messages and then presents them to the user)"""
    messages= []
    userStrMessages= ""

    def newError(self, Error): 
        self.userStrMessages = Error

    def __str__(self):
        if self.messages.count() != 0: 
            i=0
            for thing in self.messages: 
               self.userStrMessages  = self.messages[i]   "\n"
               i =1
        return self.userStrMessages

this doesn't work when I call on it like this and wants 2 input variables, but that is just self and what i put into it?:

        ErrorMessages.newError(errormessage)

errormessage is a string

i have a (what i think is) a static class? (new to this and learned in swedish which makes this harder) it looks like this

class EZSwitch(object): 
    fileway= "G:/Other computers/Stationär Dator/Files/Pyhton Program/Scheman"
    fileway2= "Kolmården.txt"
    numberSchedules= 30

I thought i could make my errormessagclass like this but it also does things with methods. Like adds things to the list messages on newError. It doesnt seem to be possible or how would I do this?

CodePudding user response:

If you want to call a method directly without making an object first then you'll have to make your method newError() a class method and then call it as you mentioned above.

@classmethod
def newError(self, Error): 
    self.userStrMessages = Error

ErrorMessages.newError(errormessage)

Otherwise you can create an object first and then call the method as:

err_object = ErrorMessage()
err_object.newError(errormessage)

CodePudding user response:

newError is an instance method. You'd need to instantiate it and then call it:

myMessage = ErrorMessage()
myMessage.newError("important error message")

See this question about making it a static/class method, which would let you call it on the class without instantiation.

  • Related