Python Classes
A class is a container for other Python objects such as variables and functions. Everything inside the class must be indented as it is part of the class "block."
Example
Here, MyClass
is a Python class. It contains a variable myValue
and
a function theAnswer
. You can create an object of this class, and set or get the
value of the variable myValue
or call the function theAnswer
.
# Define the class class MyClass: def __init__(self): self.myValue = 42; def theAnswer(self): print(self.myValue) # Creates an object called "MyObject" of type "MyClass" myObject = MyClass() # Access the object's variable "myValue" print(myObject.myValue) # Call the object's function "theAnswer" myObject.theAnswer()
Output
42 42
Notes
The __init__ method is a special method for initializin the class
The parameter self
is very important.
self
can actually be named anything you want, but the convention is to use the
term "self" meaning "myself".
A class defines the type of an object. You then create an object of that type ("instantiate an
instance" of the class). That object (the instance of the class) then has access to the
instance variables and methods of the class via the self
parameter.
def theAnswer(self): print(self.myValue)
Python automatically inserts self
into the parameter list when you call an
instance method
myObject.theAnswer()
Here we are calling theAnswer
without any parameters, but in the background
Python will pass in myObject
as the first parameter to theAnswer
,
which we then access using the self
parameter.
Everything is considered an "object" in Python - classes, functions, variables, even values.
This is because Python attaches additional information to any object, most importantly its
type. For classes and functions this can include a lot of information about the class or
function. See the built-in functions type()
, dir()
and
vars()
. Python particularly uses the type information to know what to do when
"operating" on a type.
Example
a = 1 b = 2 print(type(a)) print(type(b)) print(a + b) a = 'a' b = 'b' print(type(a)) print(type(b)) print(a + b)
Output
<class 'int'> <class 'int'> 3 <class 'str'> <class 'str'> ab
In the first example above, Python knows that 1 and 2 are numbers and adds them together. In the second example, Python knows that the types are strings and concatenates them. If Python cannot resolve what to do with an operation, it will throw an exception.
a = 1 b = 'test' print(type(a)) print(type(b)) print(a + b)
Output
Traceback (most recent call last): File "objects.py", line 5, in <module> print(a + b) TypeError: unsupported operand type(s) for +: 'int' and 'str'
In the above example, Python does know what the operator "+" means when given a number and a string.