Page Content

Tutorials

What Are The Attributes and Methods In Python With Example

Attributes and Methods

Attributes and Methods
Attributes and Methods

Object-Oriented Programming (OOP) in Python entails defining classes that act as templates for object creation. The characteristics and actions that objects of a class will possess are specified by the class. Attributes and methods, respectively, are used to express these characteristics and behaviours.

Attributes

An object or class’s attributes are its executable code or data values. They serve as a representation of the object or class’s attributes or information. Two primary categories of qualities exist:

Instance Attributes:Each instance (object) of a class has its own set of data values known as instance attributes. They can alternatively be referred to as fields, data attributes, or instance variables. Usually, instance attributes are set in the class’s init() initialisation method. Self.name = input name gives the object represented by self an instance attribute name, as demonstrated in the Duck class example. An attribute can have a default value set. Attribute values can be directly obtained and set. The dot notation, for instance, can be used to retrieve an instance attribute: object name.data attribute name. Assignment can also be used to directly modify an attribute’s value: objectname.attributename = value.

Class Attributes: These characteristics are linked to the class as a whole, not to particular instances. Unless an instance attribute with the same name overrides it, the class attribute value is shared by all instances of the class.
The standard dotted attribute notation, object.attribute, is used to access attributes, whether they are instance or class attributes. It should be noted that during search, an instance’s data attributes may take precedence over method (or class) attributes of the same name.

Methods

In essence, methods are functions that are specified inside an object or class. Methods are always linked to a class or instance, even if they are comparable to standalone functions. They stand in for the acts or behaviours that an object is capable of. Like functions, methods can take parameters.
When a new instance of a class is created, a unique method called initialisation, init(), is called automatically. Its function is to initialise the characteristics of the object at the moment of creation.

The first parameter, often called self, is a key component of methods. The instance object itself is referred to by this parameter. A method can call other methods of the same instance and access and change the instance’s properties using self.

Binding and Method Invocation

An attribute fetch and a call expression are the two primary steps involved in invoking a function in Python. From left to right, the syntax object.method(arguments) is evaluated. Python calls the object’s corresponding method after retrieving it and passing in any supplied arguments.
Python generates a bound method object when a method is accessed via an instance, such as instance object.method name. This bound method object bundles the method function (method name) with the instance (instance object). The instance object is automatically supplied as the method function’s first argument, which is a unique feature of bound methods. This is how the method’s self parameter gets the instance to which it belongs.

The underlying function can be called directly through the class by calling a bound method object (such as instance object.method name()), but the instance is explicitly passed as the first parameter (ClassName.method name(instance object)). When calling the method using the instance, you do not need to give it directly because it is already bundled in the bound method. Before they may be called directly, methods need an instance.

On the other hand, the unbound method object which is equivalent to the function object in Python 3 is returned when a method function is accessed directly through the class (ClassName.method name, for example). An instance of the class must be explicitly given as the first argument when calling this unbound method.

Code Example

Let’s use a basic Dog class to demonstrate characteristics, methods, binding, and invocation:

class Dog:
    # Class attribute shared by all Dog instances
    species = "Canis familiaris" 
    # Initialization method to set up instance attributes
    def init (self, name, breed): 
        # Instance attributes unique to each dog
        self.name = name
        self.breed = breed 
        self.is hungry = True # Default attribute value 
    # An instance method - takes self as the first argument automatically
    def bark(self): 
        # Access instance attribute using self
        print(f"{self.name} barks loudly!") 
    # Another instance method
    def eat(self): 
        if self.is hungry:
            print(f"{self.name} is eating.")
            self.is hungry = False # Modify instance attribute 
        else:
            print(f"{self.name} is not hungry.")
# Create instances (objects) of the Dog class
my dog = Dog("Buddy", "Golden Retriever")
your dog = Dog("Lucy", "Labrador")
# Access instance attributes directly
print(f"My dog's name is {my dog.name} and breed is {my dog.breed}.") 
print(f"Is my dog hungry? {my dog.is hungry}")
# Access class attribute
print(f"Both dogs are of species: {Dog.species}") 
print(f"My dog's species: {my dog.species}") # Instance can also access class attributes
# Invoke methods using the instance (Binding)
my dog.bark() # Python automatically passes 'my dog' as self 
my dog.eat()  # Python automatically passes 'my dog' as self
my dog.eat()
your dog.bark() # Python automatically passes 'your dog' as self 
# Example of calling the method via the class (Unbound method in Python 3, function object)
# Requires passing the instance explicitly
# Dog.bark(my dog) # This is equivalent to my dog.bark() 

In this example:

  • Init initialises the instance attributes name, breed, and is hungry.
  • Methods include init, bark, and eat.
  • The instance (my dog or your dog) on which the method is called is referred to as self in the methods.
  • A method invocation on a bound method is my dog.bark().
  • Python implicitly passes my dog as the self parameter to the bark function when my dog.bark() is called. The name of the particular instance (“Buddy”) is then accessed by the method using self.name.
  • Likewise, self.is hungry, the is hungry attribute unique to the my dog instance, is accessed and modified by my dog.eat().

This illustrates how methods can work with the particular data (attributes) of an instance by using the implicit self parameter that Python provides during method invocation on that instance (binding).

Kowsalya
Kowsalya
Hi, I'm Kowsalya a B.Com graduate and currently working as an Author at Govindhtech Solutions. I'm deeply passionate about publishing the latest tech news and tutorials that bringing insightful updates to readers. I enjoy creating step-by-step guides and making complex topics easier to understand for everyone.
Index