Created
April 30, 2020 09:46
-
-
Save sam-be/d47e17b8ada9517047adef3107e8bc0f to your computer and use it in GitHub Desktop.
[Python Class Construction] and defining a class function after creation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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