Here is a class:
class Dog:
species = "canis lupus" # species is a class variable
def __init__(self, name): # __init__ is the constructor
self.name = name # self.name is an object variable
def sound(self): # sound is a method (a method is a function of an object)
return "Woof, I am " + self.name
Classes are entities used to pack data and functions related to a concept together. They allow to organise projects in smaller entities than the project itself which provides the following advantages:
It worth to take time to think about a class.
A class is a mold to make objects. To make an object you just have to call the class name with argument if the initialize methods needs some.
An object can use data and functions of the class:
max = Dog('Max') # max est un objet de la classe Dog
Pour créer un objet, vous devez simplement appeler le nom de la classe avec un argument si les méthodes d'initialisation en ont besoin.
Un objet peut utiliser les données et les fonctions de la classe :
max = Dog('Maximus')
print('%s says "%s"' % (max.name, max.sound())) # Object attributes are called with a dot
print("He is a", max.species) # between the object name and its attribute
print("BTW all dogs are", Dog.species) # Same for class attributes
Maximus says "Woof, I am Maximus" He is a canis lupus BTW all dogs are canis lupus
To be able to talk about classes and object, let's define the vocabulary introduced as comment in the class Dog:
The main trick is that self
refers to the object. It is not mandatory to used the word self
but it is a convention that I strongly advice to use. By definition, the object is the first argument of methods.
If something involves self
then it is related to the object and we have:
If it does not invole self
then it is related to the class itself and we have:
All these things are attributes of the class and objects. Python says everything which is after a dot .
is an attribute.
To summarize:
type | variable name | function name |
---|---|---|
object | instance variable | method |
class | class variable | static method |
A static method can be made by two way:
@staticmethod
(better way, easier to see it is static)class Dog:
_classification = ['Animalia',
'Chordata',
'Synapsida',
'Mammalia',
'Carnivora',
'Caniformia',
'Canidae',
'Canis',
'Canis lupus',
'Canis lupus familiaris']
@staticmethod
def classification(level): # no reference to self, the object
return Dog._classification[-level:]
Dog.classification(3)
['Canis', 'Canis lupus', 'Canis lupus familiaris']
Static methods can be called from objects too:
max = Dog()
max.classification(5)
['Caniformia', 'Canidae', 'Canis', 'Canis lupus', 'Canis lupus familiaris']
{{ PreviousNext("../lesson2 Deeper in Python/12 xml.ipynb", "02 Inheritance.ipynb")}}