Menu
CoddyTech

initialize and __init__

Lesson 33 of 48 in Coddy's Python for Ruby Developers course.

Ruby Class.new allocates an instance and invokes initialize. Calling a Python class normally creates an object and then invokes __init__ to initialize it. Python __init__ receives self explicitly and must return None, usually by omitting a return statement. Store instance state on self so it survives after the method finishes. A bare local assignment inside the method does not create an instance attribute. Both examples allocate two counters and change only one. Defaults can simplify construction, but mutable defaults still follow the definition-time rule taught earlier. Put fresh mutable instance containers inside __init__.

Ruby

class Counter
  attr_accessor :value
  def initialize(value = 0)
    @value = value
  end
end
a = Counter.new(5)
b = Counter.new
puts "#{a.value} #{b.value}"

Python

class Counter:
    def __init__(self, value=0):
        self.value = value
a = Counter(5)
b = Counter()
print(a.value, b.value)

Porting trap

Do not return self from Python __init__ as a fluent-construction habit. Returning a non-None value causes a TypeError.

challenge icon

Challenge

Beginner

Implement Scoreboard(name, points=0) with instance attributes name and points. Input is a name, an integer initial score, and an integer bonus on separate lines. The driver constructs one named board with that score and another named guest using the default, adds the bonus to the first, and prints name:points for each. Scores and bonuses may be negative. Initialization must store the supplied values independently.

The locked driver reads input and prints results. Submit the required class and function definitions only; do not read input or print in your solution. Keep the API names exactly as specified.

Your code goes in the editable files scoreboard.py. driver.py holds the supplied input/output code and API checks and cannot be edited. Keep the supplied imports; do not read input or print from the editable modules.

Try it yourself

from scoreboard import Scoreboard

board = Scoreboard(input(), int(input()))
guest = Scoreboard("guest")
board.points += int(input())
print(f"{board.name}:{board.points}")
print(f"{guest.name}:{guest.points}")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Python for Ruby Developers

Practice on your own: Online Python compiler