CodeGym /Courses /Python SELF EN /Everything is Objects

Everything is Objects

Python SELF EN
Level 15 , Lesson 1
Available

1.1 Objects and Classes

Today, you'll learn how a typical Python program is structured. And the big news is: every Python program consists of classes and objects. Python is an object-oriented language, and everything in it is an object: numbers, strings, functions, and even classes are objects.

So, what are classes anyway?

Let me start with an analogy. Imagine you want to build a small ship. First, you need to create a blueprint, then hand it over to the factory, where they'll build the ship based on this blueprint. Or a dozen ships. Actually, as many ships as you want. The important thing is that dozens of identical ships can be built from one blueprint.

In Python programming, it's exactly the same.

Blueprints

A programmer is like a designer. But instead of drawing blueprints, a Python programmer writes classes. It's like parts are created based on blueprints, and objects are created based on classes.

First, we write classes (make blueprints), and then, during the execution of the program, Python creates objects based on these classes. Just like ships are created based on blueprints.

One blueprint, but there can be many ships. Ships are different, have different names, carry different cargoes. But they are very similar: they are all ships with an identical design and can perform similar tasks.

Or here's another analogy...

Ant Colony

An ant colony is a good example of how objects interact. In the simplest ant colony, there are three classes of ants: the queen, the warriors, and the worker ants.

The number of ants in each class is different. There's one queen for the whole colony, dozens of warriors, and hundreds of worker ants. Three classes and hundreds of objects. Ants interact with each other, with other ants, and with ants of other classes following strict rules.

This is a perfect example. In a typical program, things are pretty much the same. There's a main object that creates objects of all other classes. Objects start interacting with each other and with the "external world" of the program. The behavior of these objects is hardwired.

These two explanations are two sides of the same coin. The truth lies somewhere in between. The first example (about the blueprint and ships) shows the relationship between a class and the objects of that class. It's a strong analogy. The second example (about the ant colony) shows the relationship between the objects that exist during the program's runtime and the classes written.

First, you need to write classes for all the objects that will exist in the program, and then also describe their interactions. Sounds complicated, but it's easier than you think.

In Python, all entities during the program's execution are objects, and writing a program boils down to describing various ways objects interact. Objects just call each other's methods and pass in the necessary data.

Documentation

So, how do you know what data to pass to methods? There's already a solution for that.

Usually, every class has a description that states what it's for. Similarly, most public methods have a description: what they do and what data you need to pass to them.

To use a class, you need to have a general idea of what it does. And you need to know exactly what each of its methods does. It's unnecessary to know how it does it. It's like a magic wand.

Let's take a look at the code — copying a file:


src = open('source.txt', 'r')
dst = open('destination.txt', 'w')
            
for line in src:
    dst.write(line)
            
src.close()
dst.close()
        

If you read this code line by line, you can guess what it does in general terms. Although it takes some experience and practice. So after some time, this code will seem familiar and understandable to you.

1.2. Designing a Program

Designing a program is an art. It's both simple and complex at the same time. Simple, because there are no hard laws: anything that's not forbidden is allowed. And complex for the same reason: there are so many ways to do something, and it's not easy to find the best one.

Designing a program is like writing a book. On one hand, you're just writing letters, words, sentences. On the other — the plot matters, the nature of the characters, internal conflicts, style of narration, intrigue, and so on.

The main thing is to understand who you're writing code for. Remember that your code is meant for other programmers.

Developing any product is about making changes: adding here, removing there, redoing here. And so, with small iterations, big, huge, and gigantic projects are born.

The primary requirement for code is it should be understandable to other programmers. Incorrect but understandable code can be fixed. Correct but incomprehensible code can't be improved. It will just have to be thrown away.

So how do you write good and understandable code?

For this, you need to do three things:

  • Write good and understandable code within methods — the easiest part.
  • Decide what entities should be in the program.
  • Properly break the program into logical parts.

What's behind these concepts?

Writing good code within methods

If you have at least a basic level of English, you might have noticed how easy it is sometimes to read code: like sentences in English:

  • class Cat(Pet) – the Cat class extends the Pet class.
  • while stream: – while the stream is not empty ...
  • a if a < b else b – return a if a is less than b, otherwise return b.

This is done on purpose. Python is one of the few languages where you can easily write self-documenting code: code that's understandable without comments. In good Python code, many methods read just like sentences in English.

Your goal when writing code is to make it as simple and concise as possible. Just think about how easy your code will be to read, and you'll start moving in the right direction.

In Python, it's a convention to write easily readable code. Ideally, each method fits entirely on the screen (method length — 20-30 lines). This is the norm for the entire Python community. If code can be improved, it should be improved.

The best way to learn to write good code is through constant practice. Write a lot of code, study other people's code, ask more experienced colleagues to review your code. And remember that the moment you tell yourself "good enough," your growth stops.

Deciding what entities should be in the program

You need to write code that's understandable to other programmers. If 9 out of 10 programmers would create classes A, B, and C when designing a program, then you should do the same in your program. You should write code that's understandable to others.

Excellent, working, fast, non-standard code is bad code.

You need to study other projects: it's the best, the fastest, and the easiest way to absorb all the wisdom that's been accumulated in the IT industry over decades.

And by the way, you already have a great, popular, well-documented project at hand — Python SDK. Start with that.

Analyze classes and class structures. Think about why some methods are made static and others aren't. Why methods have certain parameters and not others. Why these methods, why classes are named this way and located in certain packages.

When you start understanding the answers to all these questions, you'll be able to write code that's understandable to others.

However, I want to caution you against analyzing code in methods of Python SDK. The code in many methods has been rewritten to maximize performance — its readability is questionable.

Properly dividing the program into logical parts

Any program is usually split into parts or modules. Each part is responsible for its aspect of the program.

A computer has a system unit, monitor, keyboard, and these are all separate, fairly independent parts. Moreover, their interaction is standardized: USB, HDMI, etc. Even if you spill coffee on the keyboard, you can simply wash it under the tap, dry it, and keep using it.

But a laptop is an example of monolithic architecture: there are logical parts, but they're much more integrated. For a Macbook Pro, to clean the keyboard, you need to take apart half the laptop. And spilling coffee on your laptop is a reason to order a new one. Just not coffee.

1.3 Creating Your Classes

When you're just starting to program, it's important to start small — learn to create your own classes.

Of course, you've created them already, but you need to understand what classes should be in the program, what they should be called, what methods they should have. And how they should interact with each other.

List of Entities

If you don't know where to start, start from the beginning.

At the very beginning of designing a program, you can just jot down on a piece of paper a list of entities (objects) that should be in the program. Then code them according to this principle: each entity is a separate class.

Example

Suppose you want to write a chess game. You'll need entities like: a chess board and 6 types of pieces. Pieces move differently, have different values — it's logical for them to be separate classes. In general, in the beginning, the more classes, the better.

Finding a beginner programmer who would write ten classes instead of two is rare. But writing two instead of ten, or even one — beginners love that. So more classes, fellow programmers. And your code will become clearer to everyone, maybe not to you though 😛

Chess

Suppose we decided to write classes for chess: how would these classes look?

Is a chess board simply an 8x8 array? Better to make it a separate class that holds a reference to an array internally. Then you can add many useful methods to the "chessboard" class, like checking if a square is empty or occupied.

In general, at the start, you can always follow this principle: A program has different Entities, and an Entity has a type. That type is the class.

Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION