You are currently viewing Methods and Attributes in Python

Methods and Attributes in Python

In Python, methods and attributes are two essential components of an object-oriented program.

A method is a function that is defined inside a class and can be called on an object of that class. Methods can perform operations on the object’s attributes and can return values or perform specific actions.

An attribute is a piece of data that belongs to an object. Attributes can be any data type, including numbers, strings, or other objects. Attributes can be accessed and modified by the methods of the object.

Here’s an example of a class with a method and an attribute:

class Dog:
    def __init__(self, name, breed):
        self.name = name
        self.breed = breed
        self.tricks = []

    def add_trick(self, trick):
        self.tricks.append(trick)

    def get_tricks(self):
        return self.tricks

my_dog = Dog("Fido", "Labrador Retriever")
my_dog.add_trick("roll over")
my_dog.add_trick("fetch")
print(my_dog.get_tricks()) # Output: ['roll over', 'fetch']

In this example, we have defined a Dog class with an add_trick method and a tricks attribute. We have also defined a get_tricks method to retrieve the list of tricks.

We create an object of the Dog class called my_dog with the name “Fido” and breed “Labrador Retriever”. We then call the add_trick method twice to add the tricks “roll over” and “fetch” to the tricks attribute of my_dog.

Finally, we call the get_tricks method to retrieve the list of tricks and print them to the console. The output is ['roll over', 'fetch'].

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def say_hello(self):
        print(f"Hello, my name is {self.name} and I'm {self.age} years old.")

person1 = Person("Alice", 30)
person2 = Person("Bob", 25)

person1.say_hello()   # Output: Hello, my name is Alice and I'm 30 years old.
person2.say_hello()   # Output: Hello, my name is Bob and I'm 25 years old.

In this example, we define a class Person that has two attributes name and age, and a method say_hello that prints out a message with the person’s name and age. We then create two Person objects person1 and person2 with different names and ages. Finally, we call the say_hello method on each person object, which prints a message to the console with their name and age. This demonstrates how we can define the behavior of objects using methods, and their characteristics using attributes.

Leave a Reply