Class and Instance

A class defines a type: what data its objects hold and what they can do. An instance is one object of that type, created by calling the class, as in Order("A-17", 5000.0). Every value in Python is an instance of some class, which is why type("text") reports str and a list offers append().

__init__ runs while a new instance is being set up and stores its data through self, the conventional first parameter of an instance method, which refers to the instance the call is working on. Python passes it automatically, so order.needs_review() calls the method with order as self. Assignments such as self.amount = amount create instance attributes, but two instances can still refer to the same mutable object. A class-level list is shared unless an instance shadows that attribute. Static and class methods use different binding rules.

A method is also an attribute. order.needs_review retrieves a bound method, and parentheses call it. order.amount holds a number in this example, so calling that non-callable value raises TypeError. Some attributes are callable and properties can compute values on access; “attribute” does not mean only stored data.

Define a class when several fields and the rules about them travel together, so the relationship is clear to callers. A class alone does not enforce validity: the sample’s public attributes can still be reassigned. A single calculation is clearer as a function, and a plain dictionary or tuple is often enough for a record with no behavior. To learn what an existing object offers, use dir(value) for the list, help(type(value).method) for one entry, or Tab completion in a notebook rather than memorizing names.

References: Classes, Objects, values and types. See it in use in Python Functions, Modules, and Classes.


Discover more from Insightful Data Lab

Subscribe to get the latest posts sent to your email.

Similar Posts

Questions, corrections, or additional insights?

This site uses Akismet to reduce spam. Learn how your comment data is processed.