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."
MyClass is a Python class. It contains a variable
theAnswer. You can create an object of this class, and set or get the
value of the variable
myValue or call the function
# 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()
The __init__ method is a special method for initializin the class
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
def theAnswer(self): print(self.myValue)
Python automatically inserts
self into the parameter list when you call an
Here we are calling
theAnswer without any parameters, but in the background
Python will pass in
myObject as the first parameter to
which we then access using the
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
vars(). Python particularly uses the type information to know what to do when
"operating" on a type.
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)
<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)
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.