StudyLover
  • Home
  • Study Zone
  • Profiles
  • Contact us
  • Sign in
StudyLover Attributes
Download
  1. Python
  2. OOP: A Comprehensive Guide
Objects : Methods
OOP: A Comprehensive Guide

Attributes

Attributes are the characteristics or properties of objects in object-oriented programming. They store data associated with the object and define its state.

Creating Attributes

Attributes are typically defined within the __init__ method of a class. This method is called when an object is created, and it initializes the object's attributes.

Python

class Person:

    def __init__(self, name, age):

        self.name = name

        self.age = age

In this example, name and age are attributes of the Person class.

Accessing Attributes

You can access an object's attributes using the dot notation:

Python

person = Person("Alice", 30)

print(person.name)  # Output: Alice

print(person.age)  # Output: 30

Modifying Attributes

You can modify an object's attributes by assigning new values to them:

Python

person.age = 31

print(person.age)  # Output: 31

Private Attributes

By convention, attributes prefixed with double underscores (__) are considered private and are not directly accessible from outside the class. However, they can still be accessed indirectly using getter and setter methods.

Python

class Person:

    def __init__(self, name, age):

        self.__name = name

        self.__age = age

 

    def get_name(self):

        return self.__name

 

    def set_name(self, name):

        self.__name = name  

 

Key Points:

  • Attributes define the state of an object.

  • They are accessed using the dot notation.

  • You can modify attributes by assigning new values.

  • Private attributes can be accessed indirectly using getter and setter methods.

 

Objects Methods
Our Products & Services
  • Home
Connect with us
  • Contact us
  • +91 82955 87844
  • Rk6yadav@gmail.com

StudyLover - About us

The Best knowledge for Best people.

Copyright © StudyLover
Powered by Odoo - Create a free website