Student Login

What's in a class

One of you stunningly handsome engineers asked:

"When we define a class, basically we put some properties and functions inside it. but I have seen in some cases like the ones Django uses for its forms we define another class inside it.

Can we say this is possible because, in reality, a class is a collection of objects and because a class is a class object?"

I love this question.

Because it gets at the most important tool we have as programmers... the MENTAL MODELS we use.

This coder is asking: "What's the most useful way for me to think about this?" Is it useful to think of a class as a collection of objects?

The short answer is that can be useful to think of it that way. The longer answer is that, as stated, it's not the MOST useful way.

By "useful", I mean "accurate (or accurate enough)", and "lets you accomplish what you want to accomplish".

I think it's even more useful to add in some distinctions. Accounting the natural ordering these elements have inside the class, and that sometimes matters. And acknowledging that most of the objects are member variables and methods. (I wouldn't say "functions".)

Since the most common "objects" inside a class are member variables and methods, Python has a special name for them: "attributes". An attribute is a member variable or a method. In some ways, a better way to think of a class is that it's an ordered collection of attributes - and sometimes other things, like properties and inner classes.

There's a bigger picture here. There's often more than one way to think about a coding situation. And which one you pick can make a big difference in how quickly to finish the code for that component, or project, etc.

That's why Powerful Python goes into the best mental models you can use for coding advanced Python. Not just the features of the language... but the most useful ways to reason about them.

You want to get in that habit for all the coding you do. Always be asking yourself: is there a more useful way for me to be thinking about this situation?

Book Bootcamp