Python Classes
Below is an example of a basic class used in a Python script
class Employee:
'Common base class for all employees'
__s_empCounter = 0 # static variable for incrementing IDs
# Private member variables
__id = None
__name = None
__salary = None
def __init__(self, name, salary):
self.__name = name
self.__salary = salary
Employee.__s_empCounter += 1
self.__id = Employee.__s_empCounter
def output(self):
print("ID: ", self.__id)
print("Name: " + self.__name)
print("Salary: ", self.__salary)
jo = Employee("Jo Jarvis", 20000)
sue = Employee("Sue Smith", 21000)
jo.output()
print("-------------")
sue.output()
Here are the main points to notice:
- The constructor is defined by the
__init__
keyword. Python does not the name of the class like in Java, and not__construct()
like in PHP. - Use of
__
prefix is used by programmers to show that a variable is "private" and shouldn't be changed from outside the class. However python does not enforce this as a rule and essentially all variables are public. - Every function within the class should have
self
as it's first parameter. The programmer uses this in order to manipulate the object.self
in this case is a replacement forthis
found in most other languages.- when you call a method, you treat the second argument in the list as the first. E.g. you do not need to worry about passing self.
- There is no keyword for specifying static and member variables. I have used
__s_
to denote a private static variable but I'm pretty sure I'm the only person who does this. It acts as a static variable because we reference it from the name of the class rather than by usingself
. E.g.Employee.__s_empCounter += 1
instead ofself.__s_empCounter += 1
Last updated: 25th March 2021
First published: 16th August 2018
First published: 16th August 2018