Introduction
Instance attributes store information unique to each object made from a class. They help keep data separate for each object.
Jump into concepts and practice - no test required
Instance attributes store information unique to each object made from a class. They help keep data separate for each object.
class ClassName: def __init__(self, attribute1, attribute2): self.attribute1 = attribute1 self.attribute2 = attribute2
self refers to the current object being created.
Instance attributes are usually set inside the __init__ method.
class Dog: def __init__(self, name, age): self.name = name self.age = age
class Car: def __init__(self, color): self.color = color
class Person: def __init__(self, name): self.name = name p1 = Person('Alice') p2 = Person('Bob') print(p1.name) # Alice print(p2.name) # Bob
This program creates two Book objects with different titles and authors. It prints each book's details using instance attributes.
class Book: def __init__(self, title, author): self.title = title self.author = author book1 = Book('1984', 'George Orwell') book2 = Book('Pride and Prejudice', 'Jane Austen') print(f"Book 1: {book1.title} by {book1.author}") print(f"Book 2: {book2.title} by {book2.author}")
You can add or change instance attributes anytime after creating the object.
Instance attributes belong to the object, not the class itself.
Instance attributes hold data unique to each object.
They are usually set inside the __init__ method using self.
Each object can have different values for its instance attributes.
class Dog:
def __init__(self, name):
self.name = name
dog1 = Dog("Buddy")
dog2 = Dog("Max")
print(dog1.name)
print(dog2.name)class Car:
def __init__(self, model):
model = model
car = Car("Tesla")
print(car.model)Book where each book has a title and a list of authors. How do you correctly set instance attributes so each book has its own authors list without sharing it between objects?