Contact
Evil Genius SocietyHomeLearnForumLeaderboardSocialsMessages
← Back to module

Lesson 1 of 11

So far you've kept data in variables and behaviour in functions, separately. Object-oriented programming bundles them: an object holds its own data and the functions that work on that data.

You've used objects the whole time without noticing. A string carries text and knows how to .upper() itself. A list carries items and knows how to .append(). Now you'll define your own.

Class versus object

A class is a blueprint. An object (or instance) is a thing built from that blueprint.

One Dog class; as many individual dogs as you like.

class Dog:
    pass

rex = Dog()
fido = Dog()

print(type(rex))
print(rex is fido)

class starts the definition, the name uses CapWords by convention (not snake_case), and pass is a placeholder body — the same pass from lesson 2.7.

Dog() creates a new object. rex is fido is False because they are two separate objects, even though both came from the same class.

Attributes

Data attached to an object is called an attribute. You reach it with a dot, and you can set it the same way:

class Dog:
    pass

rex = Dog()
rex.name = "Rex"
rex.age = 3

print(rex.name)
print(rex.age)

Each object has its own attributes, entirely independent:

class Dog:
    pass

rex = Dog()
fido = Dog()
rex.name = "Rex"
fido.name = "Fido"

print(rex.name)
print(fido.name)

Setting attributes from the outside like this works, but it's fragile — nothing guarantees every Dog actually has a name. The next lesson fixes that properly with __init__.

Why bother?

Compare a dictionary approach with a class approach for the same idea:

dog = {"name": "Rex", "age": 3}

def describe(d):
    return f"{d['name']} is {d['age']}"

print(describe(dog))

That works. But the function and the data are only related by convention — nothing stops you passing the wrong dictionary. A class ties them together, so the behaviour travels with the data and there is one clear definition of what a Dog is.

Use a class when you have several things that share the same shape and the same behaviour. Use a plain dictionary when you just need to hold some values.

Try it yourself

Create a Dog class, make two dogs, give each a name, and confirm they're separate objects.

Checkpoint

  • A class is a blueprint; an object is an instance built from it.
  • class Name: defines one, Name() creates an object.
  • Class names use CapWords.
  • Attributes are per-object data, reached with a dot.
  • Classes pair data with the behaviour that belongs to it.

Questions about this lesson

Log in to ask a question.