Use of self when creating objects in Python

74 views Asked by At

I made several classes which are doing the same thing, but I still don't completely understand the difference, and which is best to use. Also, the 4th object is not working. It says 'NameError: name 'self' is not defined', although I don't understand what is going wrong. This is what I wrote, the output is 7,7,7,0:

class addTwoNumbers1(object):

    def __init__(self, number1, number2):
        self.number1 = number1
        self.number2 = number2
        self.result = number1 + number2


class addTwoNumbers2(object):

    def __init__(self, number1, number2):
        self.result = number1 + number2


class addTwoNumbers3(object):

    def __init__(self, number1, number2):
        self.number1 = number1
        self.number2 = number2

    def Add(self):
        result = self.number1 + self.number2
        return result


class addTwoNumbers4(object):

    result = 0

    def __init__(self, number1, number2):
        self.number1 = number1
        self.number2 = number2

    result = self.number1 + self.number2


# Test classes for adding two numbers:

addingObject1 = addTwoNumbers1(5,2)
print addingObject1.result

addingObject2 = addTwoNumbers2(5,2)
print addingObject2.result

addingObject3 = addTwoNumbers3(5,2)
print addingObject3.Add()

addingObject4 = addTwoNumbers4(5,2)
print addingObject4.result

Thank you in advance for any advice.

1

There are 1 answers

0
Ami Tavory On BEST ANSWER

Well, your classes look like they should have been a function, but I'm assuming that's just the example. Having said that


This is useful when your object needs to store both the values that constructed it, as well as something resulting from them:

class addTwoNumbers1(object):

    def __init__(self, number1, number2):
        self.number1 = number1
        self.number2 = number2
        self.result = number1 + number2

This is useful when your object needs to store not the values that constructed it, buj just something resulting from them:

class addTwoNumbers2(object):

    def __init__(self, number1, number2):
        self.result = number1 + number2

This is useful when your object needs to store just the values that constructed it. The result should be calculated by demand and is not part of the state of the object.

class addTwoNumbers3(object):

    def __init__(self, number1, number2):
        self.number1 = number1
        self.number2 = number2

    def Add(self):
       result = self.number1 + self.number2
       return result

Nope. Doesn't make sense. This is a class variable.

class addTwoNumbers4(object):

result = 0

def __init__(self, number1, number2):
    self.number1 = number1
    self.number2 = number2

result = self.number1 + self.number2