Introduction
Attributes store information about an object. Accessing and changing them lets you see or update that information.
Jump into concepts and practice - no test required
Attributes store information about an object. Accessing and changing them lets you see or update that information.
object.attribute # to access object.attribute = new_value # to modify
Use dot . to get or set an attribute.
Make sure the attribute exists before accessing it to avoid errors.
color attribute of my_car.class Car: def __init__(self, color): self.color = color my_car = Car('red') print(my_car.color)
color attribute to a new value.my_car.color = 'blue' print(my_car.color)
age attribute of a Person object.class Person: def __init__(self, name, age): self.name = name self.age = age p = Person('Anna', 30) print(p.age) p.age = 31 print(p.age)
This program creates a Book object, shows its attributes, then changes the author and shows the new value.
class Book: def __init__(self, title, author): self.title = title self.author = author book1 = Book('Python Basics', 'Sam') # Access attributes print(f"Title: {book1.title}") print(f"Author: {book1.author}") # Modify attribute book1.author = 'Alex' print(f"Updated Author: {book1.author}")
Trying to access an attribute that does not exist will cause an error.
You can add new attributes by assigning them, like object.new_attr = value.
Use dot notation to get or set attributes on objects.
Attributes hold data about the object.
Changing attributes updates the object's information.
color of an object car in Python?object.attribute.car and attribute color, the correct syntax is car.color.age of an object person to 30?object.attribute = value.person.age to 30 by writing person.age = 30.class Dog:
def __init__(self, name):
self.name = name
my_dog = Dog("Buddy")
print(my_dog.name)
my_dog.name = "Max"
print(my_dog.name)self.name to "Buddy". So, my_dog.name is initially "Buddy".my_dog.name = "Max". The second print outputs "Max".class Cat:
def __init__(self, color):
self.color = color
kitty = Cat("black")
print(kitty[color])kitty[color], which tries to access like a dictionary key, but color is an attribute, not a key.kitty.color to access the attribute.class Book:
def __init__(self, title, author):
self.title = title
self.author = author
book1 = Book("1984", "Orwell")
book2 = Book("Animal Farm", "Orwell")
# Change author of book2 to "George Orwell"book2 author without affecting book1?book2.author modifies only that instance's attribute, not book1.Book.author changes class attribute for all instances; changing book1.author affects wrong object; brackets are invalid syntax.