Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
# Trying to explain self in Python
class Number:
class_value = 1
def __init__(self, value):
# self is used here to refer to the newly created obj because __init__ is magic and it's a constructor
# All OO langs have to have constructors
self.value = value
# In other methods, self refers to the object that was created when you called Number(some_value)
def add_to_self(self, other_number_object):
self.value += other_number_object
def add_to_other(self, other_number_object):
other_number_object.value += self.value
if __name__ == '__main__':
x = Number(1)
y = Number(1)
print("x is: " + x)
print("y is: " + y)
print("x.add_to_self(y.value) is: " + x.add_to_self(y.value))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment