Week 4 of learning Python has been very informative. I am starting to dive deeper into the Object Oriented side of things and learning about classes, class methods and how to reuse code from other files. This will also be a short post but I will try to get in as much information as possible.
When I started to learn about the classes in Python I realized it is a lot like the other languages I have learned. What I mean by this is that they have initializers, in Python an initializer method is setup like so:
class ClassName:
def __init__(self, items):
Self.the_items = items
It is important to have self because self is always pointing to the current object and that Python doesn’t use the @ syntax to refer to instance variables/attributes. If I were to have a subclass I would have to pass in the Parent class as an argument and have the methods of that subclass use self which would be referring to the Parent class self:
class ClassName:
def __init__(self, items):
Self.the_items = items
class SubClassName(ClassName):
def print_items(self):
print(self.the_items)
Now let's say you want to actually use these methods and put them in another file. To do so you would have to import these classes at the top of the new file:
from foldername.filename import ClassName, SubClassName
Then add your code. Here is an example:
from foldername.filename import ClassName, SubClassName
my_items = SubClassName([1,2,3,4,5])
# Then call the method to be able to run it
my_items.print_items()
This will then print the items you have specified when calling the subclass, SubClassName, when you run your code.
This is the main gist of what I have learned this week. I hope you got something out of this and see you next week!
Top comments (0)