Skip to content

Instantly share code, notes, and snippets.

@sam-be
Created April 30, 2020 09:46
Show Gist options
  • Save sam-be/d47e17b8ada9517047adef3107e8bc0f to your computer and use it in GitHub Desktop.
Save sam-be/d47e17b8ada9517047adef3107e8bc0f to your computer and use it in GitHub Desktop.
[Python Class Construction] and defining a class function after creation
class MathClass:
"""A simple example class"""
def __init__(self, integer1, integer2):
self.one = integer1
self.two = integer2
def print_nums(self):
print(f'The numbers are {self.one} and {self.two}')
def sum_nums(self):
return self.one + self.two
# %% test class as it stands
nums = MathClass(3, 4)
nums.print_nums()
# 'The numbers are 3 and 4'
nums.sum_nums()
# 7
# %% add a new function to the class
def product(numbers):
return numbers.one * numbers.two
MathClass.multiply_nums = product
new_nums= MathClass(5, 7)
new_nums.multiply_nums()
# 35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment