error AttributeError: 'str' object has no attribute 'value' when i use methods in other class Python

0

I'm doing a project in flask in which I already have about 50 classes with different functionalities, and when I try to return the value of a method in another class I get the error like the following:

  

AttributeError: 'str' object has no attribute 'value_one'

but if I remove the variables the .self for example, I rename the variable self.value_one to value_one if it works. the issue is that I do not know how to make using the method add in the print_Maths_Operations class, I return the calculated value without having to modify all the variables in the code. the example below represents the flaw in question that I have in several classes of the project

class Maths_Operations():

    def __init__(self):
        self.value_one  = 0
        self.value_two  = 0
        self.total = 0

    def add(self, x,y):
        self.value_one  = x
        self.value_two  = y
        self.total = self.value_one + self.value_two
        return self.total

class print_Maths_Operations():

    print(Maths_Operations.add("",4,8))
    
asked by Jose Adrian 17.10.2018 в 20:25
source

1 answer

0

Why do you pass "" as the first parameter to add() ?

I guess it's because you do not clearly understand what self represents and you have to pass some value to it, but as you have it, the value you pass is an empty string, so that when you try within the function self.value_one you're actually trying to access "".value_one and hence the error, since a string does not have that attribute.

The reason of self is to represent the object on which the operation is being attempted. That object will be an instance of the class Maths_Operations in this case.

You create an instance of that class using the syntax:

instancia = Maths_Operations()

Once you have that instance, you might think that now you can use:

print(Maths_Operations.add(instancia, 4, 8))

and actually it would work, because in this case self takes the value of the instancia you spend and you could access their fields .value_one or .value_two . But that is not the usual syntax to invoke a method that operates on the instance, but this one:

print(instancia.add(4, 8))

Notice that you put the instance variable first, and then separated by a point the method of that instance that you intend to invoke. The method in question is defined in the class, but it is executed on the instance. When you use this syntax you do not need to pass the first parameter self , since Python automatically assigns the object to the left of the point.

    
answered by 17.10.2018 в 21:07