Classes in Python
Introduction
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
What follows the dot is the attribute name. It is needed so that you can later refer to this attribute.
I have highlighted the parameter names in green. Often in examples the attribute and the parameter share the same name.
This is not a requirement, and it can get in the way of understanding the point.
Compare the following class declarations.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
pet = Dog("Tuzik", 2)
print(pet.name)
print(pet.age)
class Dog:
def __init__(self, name, age):
self.nick = name
self.years = age
pet = Dog("Tuzik", 2)
print(pet.nick)
print(pet.year)
Tuzik
2
The difference between a method and a function
A method here means an ordinary method, not a static one and not a classmethod.
A method is a function within some class.
A method expects to be applied to an object of its class
By default an object of its class has to be passed to a method.
A function expects certain arguments to be passed to it
The arguments can be both standard objects and objects of
a user-defined class.
This is determined when the function is declared
You can pass nothing at all to a function
and it will still work.
Objects
All classes in Python except Exception inherit from object
>>> o = object()
>>> dir(o)
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
Article author: Andrei Olegovich