Object Oriented Programming/Methods
Class Methods
editIf you are familiar with regular functional programming, then you are well acquainted with functions. For those who do not know(or forgot), a function is a block of code that executes a specific task when called by the program. Class methods are nearly identical to functions in practical use, but there are a few key differences. A method is a function that belongs to its class. Methods, assuming that they are dynamic and not static, can access properties as well as other methods that belong to its class. Methods can also be called manually by the user of the class, assuming it's a public and not a private method, once it has been instantiated. Below is an example of what the use of class methods can look like.
Example 1
editClass.py
editclass Values():
def __init__(self):
pass
def squared(self, value):
return = self.value * self.value
Main.py
editfrom Class.py import Values
instance = Values()
print(instance.squared(4))
# Output: 16
In the example above, a method called squared() will take the value of self.value and multiply it by itself. Here, the method is public so it is able to be called by Main.py.
Example 2
editClass.py
editclass Values():
def __init__(self):
pass
def squared(self):
return = self.add_ten(self.value * self.value)
def add_ten(self, value):
return value += 10
Main.py
editfrom Class.py import Values
instance = Values()
print(instance.squared(4))
# Output: 26
In this example, we call the method squared() but then that method calls another method add_ten(). Just like functions, methods can be called within other methods. Now, you should be able to see the functionality of methods inside of their classes.