Photo AI

Last Updated Sep 27, 2025

Attributes (OOP) Simplified Revision Notes

Revision notes with simplified explanations to understand Attributes (OOP) quickly and effectively.

user avatar
user avatar
user avatar
user avatar
user avatar

232+ students studying

Attributes (OOP)

Overview

In Object-Oriented Programming (OOP), attributes are variables that store data specific to each instance of a class. They represent the state of an object, holding values that define its unique characteristics. Attributes can be either public or private, which affects how they can be accessed and modified. Understanding attributes is essential for implementing data security, modularity, and flexibility in OOP.

Types of Attributes

Public Attributes

  • Definition: Public attributes can be accessed and modified directly from outside the class. They are often used for values that do not need any control over access or modification.
  • Accessing: These attributes are accessible using dot notation on an object of the class.
  • Drawbacks: Public attributes can lead to unintended modifications, as they can be changed from outside the class without restrictions.
lightbulbExample

Example:

class Car:
    def __init__(self, color):
        self.color = color  # Public attribute

car1 = Car("red")
print(car1.color)  # Outputs: red
car1.color = "blue"  # Directly modify the color

Private Attributes

  • Definition: Private attributes are restricted and can only be accessed or modified from within the class itself. In Python, private attributes are usually indicated by a single underscore (_) or a double underscore (__) before the attribute name.
  • Encapsulation: Private attributes support the principle of encapsulation, which restricts direct access to an object's data. Encapsulation protects the data by controlling how it is accessed and modified.
lightbulbExample

Example:

class BankAccount:
    def __init__(self, balance):
        self.__balance = balance  # Private attribute

account = BankAccount(100)
# print(account.__balance)  # Error: Attribute is not directly accessible

Using Get and Set Methods (Accessors and Mutators)

Since private attributes cannot be accessed directly from outside the class, getter and setter methods (also known as accessors and mutators) are used to control access and modification.

Getter Methods (Accessors)

Purpose: Getter methods allow external code to access the value of a private attribute without directly exposing it. This enables controlled and secure data retrieval.

lightbulbExample

Example:

class BankAccount:
    def __init__(self, balance):
        self.__balance = balance

    def get_balance(self):
        return self.__balance  # Accessor method to retrieve balance

account = BankAccount(100)
print(account.get_balance())  # Outputs: 100

Setter Methods (Mutators)

Purpose: Setter methods allow external code to modify the value of a private attribute, with any necessary validation or restrictions applied within the method. This helps enforce data integrity.

lightbulbExample

Example:

class BankAccount:
    def __init__(self, balance):
        self.__balance = balance

    def set_balance(self, amount):
        if amount >= 0:  # Only allow non-negative balance
            self.__balance = amount
        else:
            print("Invalid amount: Balance cannot be negative.")

account = BankAccount(100)
account.set_balance(200)       # Sets balance to 200
print(account.get_balance())    # Outputs: 200
account.set_balance(-50)        # Error: Invalid amount

Attributes Example

infoNote

Bank Account Class with Private Attributes and Get/Set Methods

Below is a complete example illustrating the use of private attributes and getter/setter methods to control access to an account balance.

class BankAccount:
    def __init__(self, account_holder, balance=0):
        self.account_holder = account_holder   # Public attribute
        self.__balance = balance               # Private attribute

    # Getter for balance
    def get_balance(self):
        return self.__balance

    # Setter for balance with validation
    def set_balance(self, amount):
        if amount >= 0:
            self.__balance = amount
        else:
            print("Error: Balance cannot be negative.")

    # Additional method to deposit funds
    def deposit(self, amount):
        if amount > 0:
            self.__balance += amount
            print(f"${amount} deposited. New balance: ${self.__balance}")
        else:
            print("Error: Deposit amount must be positive.")


Explanation of the Example

  • Encapsulation: The __balance attribute is private, protecting it from direct access.
  • Getter Method: get_balance allows controlled access to the balance.
  • Setter Method: set_balance validates that the balance is non-negative before updating.
  • Public Attribute: account_holder is public, so it can be accessed directly since it does not need control or validation.

Benefits of Using Private Attributes and Get/Set Methods

  • Data Security: Private attributes ensure data is not modified unintentionally or inappropriately, supporting secure data handling.
  • Data Integrity: Setter methods can validate data before modifying attributes, and maintaining correct values.
  • Encapsulation: Getters and setters protect and control access to sensitive data, keeping the internal representation hidden from outside code.

Note Summary

infoNote

Common Errors with Attributes

  • Incorrect Use of self: Forgetting to use self to refer to an attribute within a class method can cause an error.
  • Modifying Private Attributes Directly: Trying to access or modify private attributes directly outside of their class will result in an error.
  • Lack of Validation: Without validation in setters, attributes can be set to inappropriate values, potentially leading to bugs or crashes.
infoNote

Key Takeaways

  • Public attributes are directly accessible from outside the class, suitable for data that doesn't require access restrictions.
  • Private attributes are restricted to internal access only, promoting encapsulation and data security.
  • Getter and Setter methods allow controlled access and modification of private attributes, supporting data integrity and proper data management.
  • Using private attributes with get/set methods is a key part of maintaining data integrity and modularity in OOP.
Books

Only available for registered users.

Sign up now to view the full note, or log in if you already have an account!

500K+ Students Use These Powerful Tools to Master Attributes (OOP)

Enhance your understanding with flashcards, quizzes, and exams—designed to help you grasp key concepts, reinforce learning, and master any topic with confidence!

70 flashcards

Flashcards on Attributes (OOP)

Revise key concepts with interactive flashcards.

Try Computer Science Flashcards

7 quizzes

Quizzes on Attributes (OOP)

Test your knowledge with fun and engaging quizzes.

Try Computer Science Quizzes

29 questions

Exam questions on Attributes (OOP)

Boost your confidence with real exam questions.

Try Computer Science Questions

27 exams created

Exam Builder on Attributes (OOP)

Create custom exams across topics for better practice!

Try Computer Science exam builder

12 papers

Past Papers on Attributes (OOP)

Practice past papers to reinforce exam experience.

Try Computer Science Past Papers

Other Revision Notes related to Attributes (OOP) you should explore

Discover More Revision Notes Related to Attributes (OOP) to Deepen Your Understanding and Improve Your Mastery

96%

114 rated

Object Oriented Languages

Classes (OOP)

user avatar
user avatar
user avatar
user avatar
user avatar

236+ studying

194KViews

96%

114 rated

Object Oriented Languages

Objects (OOP)

user avatar
user avatar
user avatar
user avatar
user avatar

267+ studying

198KViews

96%

114 rated

Object Oriented Languages

Methods (OOP)

user avatar
user avatar
user avatar
user avatar
user avatar

248+ studying

187KViews

96%

114 rated

Object Oriented Languages

Inheritance (OOP)

user avatar
user avatar
user avatar
user avatar
user avatar

368+ studying

199KViews
Load more notes

Join 500,000+ A-Level students using SimpleStudy...

Join Thousands of A-Level Students Using SimpleStudy to Learn Smarter, Stay Organized, and Boost Their Grades with Confidence!

97% of Students

Report Improved Results

98% of Students

Recommend to friends

500,000+

Students Supported

50 Million+

Questions answered