4.1 Initialization
Usually right after they're created, objects aren't quite ready to roll. First, you need to pass in all the necessary data: operating parameters, initial values, references to other objects, and so on.
This process is called initialization and should occur immediately after an object is created.
Suppose you have a class Cat, and you want to give it a name and age, there are a few ways to do this:
Initializing attributes after creating the object
In this example, first a
- blank
Cat
object is created. - an instance of the
Cat
class namedbarsik
. - and then the object barsik has two attributes set:
name
andage
, directly added to the object.
class Cat:
pass
# Creating a Cat object
barsik = Cat()
# Initializing attributes after creating the object
barsik.name = "Barsik"
barsik.age = 5
print(f"Cat's name: {barsik.name}, age: {barsik.age}") # Output: Cat's name: Barsik, age: 5
Using a method to initialize attributes
In this example, a method initialize
is used for initializing attributes. The Cat
object is created without a single attribute, and then the initialize()
method is used to set the attribute values.
class Cat:
def initialize(self, name, age):
self.name = name
self.age = age
# Creating a Cat object
barsik = Cat()
# Initializing attributes through the method
barsik.initialize("Barsik", 5)
print(f"Cat's name: {barsik.name}, age: {barsik.age}") # Output: Cat's name: Barsik, age: 5
Using class fields
In this example, the attributes name
and age
are defined at the class level. After creating the barsik
object, the attributes are initialized directly.
class Cat:
name = ""
age = 0
# Creating a Cat object
barsik = Cat()
# Initializing object attributes
barsik.name = "Barsik"
barsik.age = 5
print(f"Cat's name: {barsik.name}, age: {barsik.age}") # Output: Cat's name: Barsik, age: 5
Which way is better? None! It's best to use a constructor :)
4.2 Constructor
A constructor is a special method that is automatically
called when a new class object is created. The constructor is used to initialize the fields of the object and can perform any initial actions needed to set up the object.
In Python, the constructor is a method named __init__
. Here are the key facts about it:
-
The
__init__
method is the constructor in Python. It's called automatically when a new instance of the class is created. -
__init__
takes at least one parameter—self
, which refers to the object being created. Additional parameters can be passed to initialize the object's attributes. -
Within the method
__init__
, you can set initial attribute values of the object usingself
. - The constructor can perform any actions needed to set up the object, like input validation or establishing relationships with other objects.
Parameters are passed to the constructor automatically, you just need to specify them inside the parentheses when creating the object.
Here's how initializing our cat with a constructor looks:
class Cat:
def __init__(self, name, age):
self.name = name
self.age = age
# Creating a Cat object with name and age
barsik = Cat("Barsik", 5)
print(f"Cat's name: {barsik.name}, age: {barsik.age}") # Output: Cat's name: Barsik, age: 5
After creating an object of type Cat
, the __init__
method will be automatically called, passing three parameters into it:
- A reference to the object barsik in the parameter
self
- The string "Barsik" in the parameter
name
- The number 5 in the parameter
age
It's convenient and neat.
Data Validation
You can also perform data validation in the constructor. After all, the goal of the constructor is to create a valid object that can be worked with further. Example:
class Cat:
def __init__(self, name, age):
if age < 0:
raise ValueError("Age cannot be negative")
self.name = name
self.age = age
# Creating a Cat object with age validation
try:
barsik = Cat("Barsik", -3)
except ValueError as e:
print(e) # Output: Age cannot be negative
GO TO FULL VERSION