Classes & objects (OOP basics)

Computer Science · Python

Question 1 of 10

0

    What does this Python code print? class Counter: def __init__(self, start): self.value = start def add(self, n): self.value += n c = Counter(8) c.add(9) c.add(1) print(c.value)

    Decimals (0.75 or 0,75), fractions (3/4) and mixed numbers (1 1/2) are accepted. Do not use thousands separators.

    How to type your answer
    • Fractions: 3/4. Mixed numbers: 1 1/2.
    • Decimals with a point or a comma: 0.75 or 0,75.
    • Negative numbers start with a minus: -3/4.
    • Percentages need the % sign: 75%.

    Stuck? Read the explanation

    Unlocks at a streak of 5 correct answers in a row.

    Print a free worksheet (PDF)

    Embed this practice on your site or class page

    Paste this HTML into your page. Students practise right there; it is free and needs no account.

    Classes & objects (OOP basics) explained

    A class is a blueprint for objects, and an object is one instance made from that blueprint. Each object holds its own data, called attributes, and can use functions defined in the class, called methods. Object-oriented programming organises a program around these objects.

    In Python you define a class with the class keyword. The init method runs when a new object is created and sets its starting attributes. Its first parameter, conventionally named self, refers to the object being created or used, so self.name stores the name on that particular object. Methods are written like functions inside the class and are called with dot notation, such as rex.birthday().

    class Dog:
        def __init__(self, name, age):
            self.name = name
            self.age = age
    
        def birthday(self):
            self.age += 1
    
    rex = Dog("Rex", 4)
    ace = Dog("Ace", 2)
    rex.birthday()
    

    Worked example

    Trace the code above.

    1. Dog("Rex", 4) creates an object with name Rex and age 4.
    2. Dog("Ace", 2) creates a second, separate object with age 2.
    3. rex.birthday() adds 1 to rex.age, so rex.age is now 5.
    4. ace.age is still 2, because each object has its own attributes.

    What you will practise

    New numbers every time you practise. Levels: Easy, Medium, Hard. Each answer is followed by a worked explanation.

    Example questions

    • Easy

      What does this Python code print? class Counter: def init(self, start): self.value = start def add(self, n): self.value += n c = Counter(6) c.add(3) c.add(6) print(c.value)

    • Medium

      What does this Python code print? class Box: count = 0 def init(self, size): self.size = size Box.count += 1 boxes = [Box(5), Box(5), Box(5), Box(4)] print(Box.count + boxes[2].size)

    • Hard

      What does this Python code print? class Score: total = 0 def init(self, bonus): self.bonus = bonus def bump(self): self.total += self.bonus s1 = Score(5) s2 = Score(1) s1.bump() s1.bump() s1.bump() s2.bump() s2.bump() print(Score.total)