2 Classes and Objects
Build a practical understanding of Python classes and objects, including instance creation, state, methods, initialization, identity, references, and independent object behavior.
Classes, objects, and instances
-oriented programming organizes software around objects that combine data with operations. A describes the common structure and behavior, while each is a concrete runtime value created from that description.
A defines a programmer-created type. It can specify:
attributes, which hold named data;
methods, which define operations; and
initialization logic, which establishes a valid starting .
An is a concrete value created from a . Because it is an individual example of a , it is also an . For example, a BankAccount can describe what every account has, such as an owner and balance, and what every account can do, such as deposit and withdraw money.
The is reusable; it is not itself one particular bank account. Creating an individual account from it is called .
Takeaway: A describes a type, and an is one created of that type.
Attributes and
An is a named value associated with a or one of its objects. The collection of an 's values at a particular moment is its .
For an account, owner and balance can be attributes. If one account has a balance of and another has a balance of , their states differ even though both objects come from the same .
A can also provide shared data. A such as currency = "USD" is associated with the and can be visible through its instances. By contrast, attributes belong to individual objects and are appropriate for values that vary from to .
Be careful with mutable attributes such as lists or dictionaries. Because the same mutable value can be shared, a change made through one may be visible through other instances. Data that should be independent usually belongs on the .
Takeaway: Attributes represent data, is the data's current arrangement, and data should be used for values that must remain independent.
Methods and behavior
A is a function associated with a . It defines behavior that an can perform or that can be performed on its behalf. Dot notation places the before the name, as in account.withdraw(100).
In Python, an conventionally receives the as its first parameter, usually named self. When the is called through an , Python supplies that argument automatically.
Methods can:
return information without changing ;
change , such as increasing an account balance;
validate input and reject invalid operations; or
coordinate several internal operations.
Using a instead of directly changing an can preserve the 's rules. For example, a withdrawal can reject an amount greater than the current balance, preventing an invalid .
Takeaway: Methods are the behavior of an and provide a controlled way to inspect or change its .
Construction and initialization
A is creation-time logic that establishes an 's initial values. In Python, __init__() is an initializer called automatically after a new has been created. In Java, a has the same name as its and has no return type.
A well-designed initializer establishes a valid starting . For example, a Student initializer can receive a name and year, then store those values in the new 's attributes.
Validation can occur during initialization. A rectangle initializer might reject nonpositive dimensions before storing width and height. This ensures that every successfully created rectangle begins in a the considers valid.
Some languages provide a default or no-argument when none is explicitly declared. The exact rule depends on the language; Java supplies one only when the declares no constructors.
Takeaway: Initialization is part of creation and should establish required data and enforce important starting conditions.
Identity, equality, and references
Two objects can contain equal-looking values while still being different objects. concerns whether two references designate the exact same , whereas equality concerns whether their values compare as equal according to the type's rules.
For example, two separately created accounts for the same owner and balance have different identities. If third = first, then third is another to the designated by first; it is not a new copy. A change made through either affects the same .
In Python, is and is not test identity, while == tests equality. The id() function returns an integer that is unique and constant for an during that 's lifetime.
An assignment such as alias = account creates a to the existing . A genuine copy requires an explicit copying operation, and the result may be shallow or deep depending on the language and the data inside the .
Takeaway: Equal values do not guarantee equal identity, and assigning a new name usually creates an alias rather than a copy.
Putting the concepts together
A complete workflow can be understood through a rectangle example:
Define a
Rectanglewithwidthandheightattributes.Instantiate objects such as a small rectangle with dimensions and , and a large rectangle with dimensions and .
Let the initializer validate the dimensions and establish the initial .
Use an
area()to calculate the current area. For the small rectangle, .Use a
scale()to change the dimensions. Scaling the small rectangle by changes its area to .Observe that the large rectangle remains at area , because it is a separate with independent .
This sequence connects the main ideas: the defines the available structure and behavior, creates objects, initialization sets their starting data, methods inspect or mutate , and separate instances normally do not affect one another.
Takeaway: Follow the lifecycle from definition to , initialization, use, change, and independent instances.