Introduction
Creating objects lets you make your own things in code that can hold data and actions. It helps organize and reuse code easily.
Jump into concepts and practice - no test required
Creating objects lets you make your own things in code that can hold data and actions. It helps organize and reuse code easily.
class ClassName: def __init__(self, parameters): self.attribute = value object_name = ClassName(arguments)
class defines a new type of object.
__init__ is a special function that runs when you create an object.
class Dog: def __init__(self, name): self.name = name my_dog = Dog("Buddy")
class Car: def __init__(self, color, year): self.color = color self.year = year my_car = Car("red", 2020)
This program creates a Person object with a name and age, then prints a greeting using those details.
class Person: def __init__(self, name, age): self.name = name self.age = age def greet(self): print(f"Hello, my name is {self.name} and I am {self.age} years old.") person1 = Person("Alice", 30) person1.greet()
Use self to refer to the object itself inside methods.
Each object can have its own unique data stored in attributes.
Objects are created from classes which act like blueprints.
The __init__ method sets up the object when it is made.
Objects help organize data and actions together.
__init__ method in a Python class?__init____init__ method is called automatically when a new object is created from a class.__init__ does__init__ initializes object attributes [OK]__init__ sets up new objects [OK]__init__ deletes objects__init__ with printing methods__init__ defines new classesCar in Python?new Car() is Java/C++ style, invalid in Python. Car.create() assumes a non-existent method. Car[] is invalid. Only Car() works.ClassName() to create objects [OK]class Dog:
def __init__(self, name):
self.name = name
d = Dog('Buddy')
print(d.name)Dog class has an __init__ method that sets self.name to the given argument.d = Dog('Buddy') runs, d.name becomes 'Buddy'. Printing d.name outputs 'Buddy'.class Person:
def __init__(self, age):
age = age
p = Person(30)
print(p.age)__init__age = age, which only changes the local variable, not the object's attribute.self.age = age to store the value in the object.self.attribute = value to store data [OK]Book that stores title and author. Which code correctly creates an object and prints the title and author?__init__ with title and author parameters and assigns self.title = title and self.author = author.Book('1984', 'Orwell') matching the parameters, and both attributes print correctly. Others fail on missing self, incomplete assignments, or parameter mismatch.