Intro
In a continuation of the last post about python, I will be covering some slightly more advanced material. This post is about python classes, class inheritance, and modules.
Classes
What's a Class?
Classes are like a framework for making a personalized object, or as w3school puts it, "like an object constructor, or a 'blueprint' for creating objects". Classes essentially serve as an object containing a series of properties and methods (functions).
Creating a class is rather simple for python, as a class is declared by the 'class' keyword followed by the name of the class and any properties or methods that are desired or needed.
#Creating a class
class Example:
x = 1 #any variable declared in the class serves as a property
y = "example text"
z = True
Properties
As the example above shows, properties are the variables declared and stored in the object. Properties can be any of the data types used in python and can be accessed like so:
#Accessing properties from outside the class
print(Example.x) #prints 1 to console
Property Manipulation
While class properties are often declared and manipulated inside the class definition, it is possible to add, delete, or modify class properties outside of the definition. It should be noted however, that these manipulations can end up changing the definition or a particular instance of a class depending on how the manipulation is done.
#Manipulating Properties of a Class Definition
class Example:
x = 1
Example.y = 2 #adds new y property to Example
del Example.y #removes y property from Example
Example.x = 3 #modifies existing x property of Example
#Manipulating Properties of a Class Instance
ex1 = Example() #create an instance of the Example class
ex1.y = 2 #adds new y property to ex1 (this particular instance of Example)
print(Example.y) #will cause an error due to y property not existing for Example)
ex1.x = 1 #will modify value of x property for ex1 (this instance)
print(Example.x) #will print 3
print(ex1.x) #will print 1
del ex1.y #delete y property of ex1
del ex1 #delete entire object
Methods
Methods are functions contained inside a class, capable of doing anything a normal function would
#Creating and using a method
class Example:
def func():
print('Hello')
Example.func() #prints 'Hello'
ex1 = Example()
ex.func() #prints 'Hello'
The init Method
In some cases, it may be necessary to have a class take in a value or perform an action when a class instance is created. To do that, all python classes possess the init method, which will be run whenever a class instance is made.
#Using the __init__ method
class Example:
def __init__(self, x, y): #The self parameter is used to refer to the properties of class inside the class definition
self.x = x
self.y = y
print('new instance of Example made')
def add(self): #whenever a method wants to use properties in the class definition, self must be the first parameter
print(self.x + self.y)
ex1 = Example(1, 2) #will print 'new instance of Example made' due to init
ex1.add() #will print 3 to console
Pass
A relatively minor class inclusion is pass. Pass is a statement used if a class definition is empty. Normally a class definition requires at least a single line of code inside to not result in an error but pass effectively allows for an empty definition
#Pass example
class Example:
pass #this results in a no content class, for whatever reason one would be wanted
Class Inheritance
There are cases where a coder may have a bunch of classes that share a number of similar features but also have a number of features that are not shared. To help out with these kinds of situations it is possible to create a class that would possess all of the similar features that could then be used by all of the other objects. This functionality is called class inheritance. Class inheritance works by creating a 'parent function' that contains all the properties and methods that a series of objects share, and child classes that will inherit from the parent class all of these shared items while having its own properties and methods that only the child has.
#Parent Class
class Parent:
def __init__(pers, x, y):
pers.x = x
pers.y = y
#parent method
def meth():
print('parent method')
#parent classes are just like a normal class
Child Classes
#Inheritance demonstration
class Child(Parent):
pass
ex1 = Child(1, 2)
ex1.meth() #print 'parent method'
#as Child is now it has only the inherited properties and methods from Parent
class Child2(Parent):
def __init__(self, x, y):
#the init of Child2 will overwrite the init for Parent. to include the init of Parent this must be used:
Parent.__init__(self, x, y)
#anything added from this point on in the init will only apply to the init of Child2
def meth():
#another way to have an overwritten method/property inherited is with the super keyword
super().meth() #meth method takes in from meth function in Parent
ex2 = Child2(2, 4)
ex2.meth() #prints 'parent method'
Modules
What's a Module?
Modules are pythons equivalent to a library, containing functions and variables that can be used in a coder's files. Python features its own slew of built-in modules available for anyone to use, however, it is possible for people to create their own modules for personal use.
Using a Module (Importing)
To use a module is quite simple. Say a coder would want access to python's math module to make use of one of its additional methods, say the square root method. How to do that someone would do as so:
#importing a module
import math
Ta-da, quite simple indeed. Just use import and the module name and the file can now use any function from the math module. Now, to use the square root method in math, one would do this:
a = math.sqrt(4) #use the module name followed by the function name to access the function
print(a) #prints 2
Using Modules: Additional Information
Some minor but helpful bits for module usage are aliases, function lists, and importing parts of a module.
Aliases
Aliases are a way to refer to a module by a different name. Say a module name is rather difficult to spell correctly or a coder just wants an easy shorthand to use for a module. To use an alias is rather simple, using the as keyword.
#Using aliases
import modulename as mn #a module alias can be anything
mn.func() #using an alias to call a function from the module
Function list
Sometimes a coder may import a module with a large number of functions or variables without knowing the names of them all. To help know everything a module contains python thankfully has the dir function to help. Dir provides a list of all variable and function names in a given module.
#Using dir
import math
funcList = dir(math)
print(funcList) #prints a list of all function/variable names in the math module
Importing Parts of a Module
Sometimes a coder may want to access a specific function or variable from a module and so does not want or need the whole module for a file. Python provides a simple way to import part of a module rather than the entire thing.
#importing part of a module
from math import sqrt
print(sqrt(4)) #prints 2
#when using a function or variable imported this way, the module name is not used to invoke the imported value
Making a Module
Making a module is rather easy. To do so a coder would create a python file with variables or functions created as normal followed by naming the file whatever is desired before ending the name in .py
. From there all the coder would need to do is in another file use import modulename
without the .py
and presto! A module has been made and imported.
Built-in Modules
Python has a whole slew of modules but some that may be helpful for general purposes are:
- math : a series of helpful math functions
- datetime : adds a date object to use and manage dates
- json : use json formatting in python
Top comments (0)