Tools
Log in
English

Learn to codePython

Python composition and class variables

Based on Python 3.12

A robot with a battery: composition, class variables, staticmethod, classmethod.

In one line

Composition means keeping another object as an attribute and handing it work. A class variable lives once on the class rather than on each object, and @staticmethod and @classmethod are methods you call without an object.

Why you need it

Inherit with class Robot(Battery) and the robot exposes level and use() directly. The moment you want two batteries or a different kind, the inheritance line has to be torn out.

Keep the battery as an attribute and the robot only needs self.battery.use(). Swap in another battery class and the robot code stays the same.

Everyday picture

Think of a cordless drill. The drill has a battery pack, and when it runs flat you clip in another. If the drill had inherited from the battery, a dead battery would mean a dead drill.

Example code

main.py · 38 lines
class Battery:    def __init__(self, capacity):        self.capacity = capacity        self.level = capacity     def use(self, amount):        self.level = max(0, self.level - amount)        return self.level  class Robot:    made = 0     def __init__(self, name, capacity=100):        self.name = name        self.battery = Battery(capacity)        Robot.made += 1     @staticmethod    def valid_name(name):        return name.isalnum() and len(name) <= 8     @classmethod    def from_text(cls, text):        name, cap = text.split(":")        return cls(name, int(cap))     def work(self, hours):        left = self.battery.use(hours * 15)        return f"{self.name} worked {hours}h, battery {left}/{self.battery.capacity}"  r1 = Robot("Dori")r2 = Robot.from_text("Mong:60")print(r1.work(3))print(r2.work(5))print("Robots made:", Robot.made)print(Robot.valid_name("Mini-1"), Robot.valid_name("Bolt7"))

When to use it

  • "Has a" fits: a robot and its battery, an order and its address, a game character and its bag
  • A value every object should share (a counter, a setting): use a class variable
  • Helpers that need no object: @staticmethod; another way to build objects from different input: @classmethod

In Python, a helper used across several modules is more often a plain function outside the class. Keep @staticmethod for helpers that clearly belong to that one class.

Common mistakes

Keeping a mutable list as a class variable

tools = [] in the class body is one list shared by every robot. Values each robot should own go in __init__ with self..

Wrong

class Robot:    tools = []     def add(self, tool):        self.tools.append(tool)  a = Robot()b = Robot()a.add("drill")print(b.tools)

When you run it['drill']

Fixed

class Robot:    def __init__(self):        self.tools = []     def add(self, tool):        self.tools.append(tool)  a = Robot()b = Robot()a.add("drill")print(b.tools)

When you run it[]

Incrementing a class variable through self.

self.made += 1 reads the class value, adds 1 and stores the result as a new attribute on the object. Robot.made stays 0. Change it through the class name.

Wrong

class Robot:    made = 0     def __init__(self):        self.made += 1  Robot()Robot()print(Robot.made)

When you run it0

Fixed

class Robot:    made = 0     def __init__(self):        Robot.made += 1  Robot()Robot()print(Robot.made)

When you run it2

Forgetting @staticmethod

Without the decorator it is a normal method, so the object is slipped in as the first argument. Helpers that need no object get @staticmethod.

Wrong

class Robot:    def valid_name(name):        return name.isalnum()  print(Robot().valid_name("Dori"))

When you run itTypeError: Robot.valid_name() takes 1 positional argument but 2 were given

Fixed

class Robot:    @staticmethod    def valid_name(name):        return name.isalnum()  print(Robot().valid_name("Dori"))

When you run itTrue

Check yourself

Question 1

Starting fresh with the example classes, after Robot("Ari") and Robot.from_text("Bo:40"), what is Robot.made?

Robot("Ari")Robot.from_text("Bo:40")print(Robot.made)

Show the answer

Answer: 2. 2 from_text also goes through __init__ via cls(...). Each call adds 1, so it is 2.

Question 2

Which decorator passes the class itself as the first argument?

Show the answer

Answer: 2. @classmethod @classmethod receives cls. Called on a subclass, cls is that subclass, so constructors like from_text keep working for children.

Questions people ask

What is the difference between @staticmethod and @classmethod?

@staticmethod receives nothing automatically; @classmethod receives the class as cls. Use @classmethod for alternative ways to build objects.

Why is a list as a class variable a problem?

Every object shares that single list, so a value added through one object shows up in all of them. Create per-object values in __init__.

Is composition always better than inheritance?

No. When "is a" clearly fits, inheritance is tidy. For parts you may swap or have several of, composition fits.