Methods and Attributes
Now that you know what a class is and how to create objects, it’s time to delve into two key concepts: attributes and methods. These are the fundamental components that give functionality and characteristics to your objects.
What are Attributes?
Section titled “What are Attributes?”Attributes are variables that store information about the state of an object. Each object can have different values for its attributes.
class Person:def __init__(self, name, age):self.name = nameself.age = age
p1 = Person('Ana', 30)print(p1.name) # Anaprint(p1.age) # 30
In this example, name
and age
are attributes of each Person
object.
What are Methods?
Section titled “What are Methods?”Methods are functions defined within a class that describe the behaviors of objects. They always receive at least one parameter: self
, which represents the object itself.
class Person:def __init__(self, name):self.name = name
def greet(self):print(f'Hello, I am {self.name}!')
p1 = Person('Ana')p1.greet() # Hello, I am Ana!
Types of Attributes
Section titled “Types of Attributes”- Instance attributes: Are unique to each object (like
self.name
). - Class attributes: Are shared by all instances of the class.
class Pet:species = 'Dog' # Class attribute
def __init__(self, name):self.name = name # Instance attribute
m1 = Pet('Rex')m2 = Pet('Luna')print(m1.species) # Dogprint(m2.species) # Dog
Types of Methods
Section titled “Types of Methods”- Instance methods: Use
self
and operate on the object. - Class methods: Use
@classmethod
and receivecls
as the first parameter. - Static methods: Use
@staticmethod
and receive neitherself
norcls
.
class Calculator:@staticmethoddef add(a, b):return a + b
@classmethoddef description(cls):return 'Simple calculator'
print(Calculator.add(3, 4)) # 7print(Calculator.description()) # Simple calculator
Best Practices
Section titled “Best Practices”- Use descriptive names for attributes and methods.
- Private attributes (for internal use only) are named with an underscore:
_attribute
. - Document your methods using docstrings.
Summary
Section titled “Summary”- Attributes: store object information.
- Methods: define object behaviors.
- There are instance, class, and static attributes and methods.
- Mastering these concepts allows you to create more useful and flexible classes.
Ready to continue? Try creating a class with your own attributes and methods!