Home > Back-end >  update the value of an empty attribute class using a method
update the value of an empty attribute class using a method

Time:07-15

Does anyone know how to update the value of an empty class instance in a method? My code does not work as expected.

class addition:
    def __init__(self):
        self.number = None
    def add(self, data):
        
        if self.number == None:
            print('no')
            self.number = data
        else:
            print('yes')
            self.number   10
        return self.number 

addition().add(4)
addition().add(5)

With addition().add(5) I want self.number to be equal to 4 but it stays equal to none. Please help!

CodePudding user response:

You should either instantiate an object of your class or use a class method.

When you use a non static class, the members of your class receive the self identifier, meaning that they belong to that specific instance, that needs to be created. Like:

class addition:
    def __init__(self):
        self.number = None
    def add(self, data):
        
        if self.number == None:
            print('no')
            self.number = data
        else:
            print('yes')
            self.number   10
        return self.number 

addition1 = addition()
addition1.add(4)
addition1.add(5)

Otherwise, you can use a variable as a member of the class itself and declare the method a class method, then you don't need to instantiate an object and can call it directly. With a class method you don't use the word self, because you don't have an instance. Instead, you use (by convention) the word cls, referring to the class. Example:

class addition:
    number = None
    
    @classmethod    
    def add(cls, data):
        
        if cls.number == None:
            print('no')
            cls.number = data
        else:
            print('yes')
            cls.number   10
        return cls.number 

addition.add(4)
addition.add(5)
  • Related