Public attributes let you store and access information inside an object easily. They are open for anyone to read or change.
Public attributes in 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.
Dog class with public attributes name and age. We create a dog and access/change its attributes directly.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
Car class has a public attribute color. We change the car's color after creating it.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
This program creates a Person object with public attributes name and age. It prints the values, changes the age, and prints the new age.
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}')
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.
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.