3 min read•june 24, 2024
Classes in Python are blueprints for creating objects, encapsulating data and behavior. They define attributes and methods that of the will have, allowing for organized and reusable code in .
Instances are individual objects created from a , each with its own set of attributes. By using classes and instances, programmers can model real-world entities and their interactions, making code more intuitive and easier to maintain.
class
keyword followed by class name ( convention)Person
, Car
, BankAccount
[__init__()](https://www.fiveableKeyTerm:__init__())
is a special constructor that initializes attributes
[self](https://www.fiveableKeyTerm:self)
as the first parameter, referring to the instance being createddef __init__(self, name, age)
to initialize name
and age
attributes__init__()
using self.attribute_name
syntaxself.name = name
and self.age = age
inside __init__()
self
as the first parameterself
keyword
def introduce(self): print(f"My name is {self.name} and I am {self.age} years old.")
__init__()
to initialize instance attributes
person1 = Person("Alice", 25)
creates a Person
instance with name
"Alice" and age
25instance_name.attribute_name
person1.name
accesses the name
of person1
instance_name.method_name(arguments)
person1.introduce()
calls the introduce
method on person1
person2 = Person("Bob", 30)
creates another Person
instance with different attribute values__init__()
using self.attribute_name
self.name
and self.age
are instance attributesinstance_name.attribute_name
person1.name = "Alice"
modifies the name
attribute of person1
species = "Human"
defined directly in the Person
classClassName.attribute_name
Person.species
accesses the species
instance_name.attribute_name
person1.species
also accesses the species
name
, age
, etc.)species
, default values, etc.)Person.species
affects all Person
instances, but changing person1.name
only affects person1