Attributes and methods of classes in Python
Attributes and methods are the main components of classes in Python. Attributes are data associated with an object, and methods are functions that perform actions on objects. Understanding these concepts is critically important for mastering object-oriented programming in Python.
Attributes in Python
Attributes are variables that belong to a class object. They store the state of an object and can be accessed via dot notation (object.attribute). The class attributes are defined in the __init__() method or can be created dynamically.
Declaring and initializing attributes
Attributes are usually declared and initialized in the __init__() method., which is the constructor of the class. The constructor is automatically called when a new instance of the class is created.
class Circle:
def __init__(self, radius):
self.radius = radius # The "radius" attribute is initialized when the object is created
my_circle = Circle(5) # Creating an object with a radius of 5
print(my_circle.radius) # Output: 5
In this example, the radius attribute is initialized to 5 when creating the my_circle object.
Access to object attributes
Attributes are accessed using dot notation. Attributes can be either read or changed after the object is created.
class Circle:
def __init__(self, radius):
self.radius = radius
my_circle = Circle(5)
print(my_circle.radius) # Output: 5
# Changing the value of the my_circle attribute
.radius = 10
print(my_circle.radius) # Output: 10
Class and instance attributes
In Python, there are class attributes and instance attributes. Class attributes belong to all instances of the class, and instance attributes belong to a specific object.
class Circle:
pi = 3.14159 # Class attribute
def __init__(self, radius):
self.radius = radius # Instance attribute
circle1 = Circle(5)
circle2 = Circle(10)
print(circle1.pi) # Output: 3.14159
print(circle2.pi) # Output: 3.14159
print(Circle.pi) # Output: 3.14159
Methods in Python
Methods are functions defined inside a class. They provide an interface for performing actions on an object and can use the object's attributes for their work.
Declaring Methods
Methods are declared inside the class using the keyword def. The first parameter of the method is usually self, which refers to the current instance of the object.
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14159 * self.radius ** 2 # Method for calculating the area of a circle
def get_info(self):
return f"Circle with radius {self.radius}"
my_circle = Circle(5)
print(my_circle.area()) # Output: 78.53975
print(my_circle.get_info()) # Output: A circle with a radius of 5
Calling methods
Methods are called on an object using dot notation (object.method()). When calling a method, Python automatically passes a reference to the object as the first argument.
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14159 * self.radius ** 2
my_circle = Circle(5)
print(my_circle.area()) # Output: 78.53975
Methods with parameters
Methods can accept additional parameters to perform various operations.
class Circle:
def __init__(self, radius):
self.radius = radius
def scale(self, factor):
"""Scaling the radius of the circle"""
self.radius *= factor
def area(self):
return 3.14159 * self.radius ** 2
my_circle = Circle(5)
print(my_circle.area()) # Output: 78.53975
my_circle.scale(2) # Increase the radius by 2 times
print(my_circle.area()) # Output: 314.159
Full example with the Circle class
class Circle:
pi = 3.14159 # Class attribute
def __init__(self, radius):
self.radius = radius # Initializing the radius attribute
def area(self):
"""Calculating the area of a circle"""
return self.pi * self.radius ** 2
def circumference(self):
"""Calculating the circumference"""
return 2 * self.pi * self.radius
def diameter(self):
"""Calculating the diameter of a circle"""
return 2 * self.radius
def scale(self, factor):
"""Scaling the radius"""
self.radius *= factor
# Creating an object and using
the my_circle = Circle(5) methods
print(f"Radius: {my_circle.radius}") # Output: Radius: 5
print(f"Area: {my_circle.area():.2f}") # Output: Area: 78.54
print(f"Circumference: {my_circle.circumference():.2f}") # Output: Circumference: 31.42
print(f"Diameter: {my_circle.diameter()}") # Output: Diameter: 10
A practical example with the Person class
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def say_hello(self):
"""Greeting method"""
print(f"Hello, my name is {self.name }, I am {self.age} years old.")
def birthday(self):
"""Age increase by 1 year"""
self.age += 1
print(f"Happy birthday! Now I am {self.age} years old.")
def get_info(self):
"""Getting information about a person"""
return f"Name: {self.name }, Age: {self.age}"
def is_adult(self):
"""Age verification"""
return self.age>= 18
# Creating an object and calling methods
person1 = Person("Alice", 30)
person1.say_hello() # Output: Hi, my name is Alice, I am 30 years old.
# Calling the birthday
person1 method.birthday() # Conclusion: Happy birthday! Now I'm 31 years old.
# Using other
print(person1) methods.get_info()) # Output: Name: Alice, Age: 31
print(f"Adult: {person1.is_adult()}") # Output: Adult: True
# Direct access to attributes
print(f" Name: {person1.name }") # Output: Name: Alice
print(f"Age: {person1.age}") # Conclusion: Age: 31
Additional example with the Rectangle class
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
"""Calculating the area of a rectangle"""
return self.width * self.height
def perimeter(self):
"""Calculating the perimeter of a rectangle"""
return 2 * (self.width + self.height)
def is_square(self):
"""Checking whether a rectangle is a square"""
return self.width == self.height
def resize(self, width_factor, height_factor):
"""Rectangle resizing"""
self.width *= width_factor
self.height *= height_factor
# Using the Rectangle class
rectangle = Rectangle(10, 5)
print(f"Area: {rectangle.area()}") # Output: Area: 50
print(f"Perimeter: {rectangle.perimeter()}") # Output: Perimeter: 30
print(f" Square: {rectangle.is_square()}") # Output: Square: False
rectangle.resize(2, 3)
print(f"New dimensions: {rectangle.width}x{rectangle.height}") # Conclusion: New dimensions: 20x15
Key points
Attributes store object data and determine its state. They can be initialized in the __init__() constructor. or created dynamically.
Methods define the behavior of an object and can change its state by working with attributes.
The self parameter should always be the first parameter in the instance methods, it refers to the current object.
The dot notation is used to access attributes and methods of an object.
Understanding attributes and methods is the foundation for effective use of object-oriented programming in Python and creating well-structured code.