Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Oppiskele Constructor | Classes and Objects
Object-Oriented Programming in Python

bookConstructor

Constructor is a unique method that is automatically called during object creation. This method is not obligatory to define. The object can be created with the constructor generated automatically, as we did before.

Constructor syntax

Constructor has reserved name __init__().

Code

After the object is created, it contains name and hair_color attributes, that are created during the constructor call. If we don't input any values of name or hair_color, these attributes automatically have default values: 'Kitty', 'black'.

123456
class Cat: def __init__(self, name = 'Kitty', hair_color = 'black'): self.name = name self.hair_color = hair_color print(Cat)
copy

Test the code below!

12345678910
class Cat: def __init__(self, name = 'Kitty', hair_color = 'black'): self.name = name self.hair_color = hair_color print(name, 'cat with the', hair_color, 'hair') # An object without adding attribute values cat1 = Cat() # An object with adding attribute values cat2 = Cat('Eva', 'white')
copy

Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 1. Luku 5

Kysy tekoälyä

expand

Kysy tekoälyä

ChatGPT

Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme

Suggested prompts:

Kysy minulta kysymyksiä tästä aiheesta

Tiivistä tämä luku

Näytä käytännön esimerkkejä

Awesome!

Completion rate improved to 7.69

bookConstructor

Pyyhkäise näyttääksesi valikon

Constructor is a unique method that is automatically called during object creation. This method is not obligatory to define. The object can be created with the constructor generated automatically, as we did before.

Constructor syntax

Constructor has reserved name __init__().

Code

After the object is created, it contains name and hair_color attributes, that are created during the constructor call. If we don't input any values of name or hair_color, these attributes automatically have default values: 'Kitty', 'black'.

123456
class Cat: def __init__(self, name = 'Kitty', hair_color = 'black'): self.name = name self.hair_color = hair_color print(Cat)
copy

Test the code below!

12345678910
class Cat: def __init__(self, name = 'Kitty', hair_color = 'black'): self.name = name self.hair_color = hair_color print(name, 'cat with the', hair_color, 'hair') # An object without adding attribute values cat1 = Cat() # An object with adding attribute values cat2 = Cat('Eva', 'white')
copy

Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 1. Luku 5
some-alt