0
0
Pythonprogramming~5 mins

Public attributes in Python

Choose your learning style9 modes available
Introduction

Public attributes let you store and access information inside an object easily. They are open for anyone to read or change.

When you want to keep simple information about an object that everyone can see and update.
When you create a class to represent something like a person, car, or book and want to store details like name or color.
When you want to quickly share data inside your program without hiding it.
When you are learning about classes and want to understand how objects hold data.
When you want to change or check an object's details directly without special methods.
Syntax
Python
class ClassName:
    def __init__(self, attribute1, attribute2):
        self.attribute1 = attribute1  # public attribute
        self.attribute2 = attribute2  # public attribute

Public attributes are defined inside the __init__ method using self.attribute_name.

They can be accessed or changed from outside the class using object.attribute_name.

Examples
This example shows a Dog class with public attributes name and age. We create a dog and access/change its attributes directly.
Python
class Dog:
    def __init__(self, name, age):
        self.name = name  # public attribute
        self.age = age    # public attribute

my_dog = Dog('Buddy', 3)
print(my_dog.name)  # prints Buddy
my_dog.age = 4
print(my_dog.age)   # prints 4
Here, the Car class has a public attribute color. We change the car's color after creating it.
Python
class Car:
    def __init__(self, color):
        self.color = color  # public attribute

car1 = Car('red')
print(car1.color)  # prints red
car1.color = 'blue'
print(car1.color)  # prints blue
Sample Program

This program creates a Person object with public attributes name and age. It prints the values, changes the age, and prints the new age.

Python
class Person:
    def __init__(self, name, age):
        self.name = name  # public attribute
        self.age = age    # public attribute

person1 = Person('Alice', 30)
print(f'Name: {person1.name}')
print(f'Age: {person1.age}')

# Changing public attribute
person1.age = 31
print(f'New Age: {person1.age}')
OutputSuccess
Important Notes

Public attributes can be accessed and changed from anywhere in your code.

Be careful when changing public attributes because it can affect other parts of your program.

For more control, you can learn about private attributes later, but public attributes are great for simple use.

Summary

Public attributes store information inside objects that anyone can access or change.

They are easy to use and good for simple data storage in classes.

Use self.attribute_name inside __init__ to create public attributes.