Introduction
Object-oriented programming helps organize code by grouping related data and actions together. It makes programs easier to understand, reuse, and change.
Jump into concepts and practice - no test required
Object-oriented programming helps organize code by grouping related data and actions together. It makes programs easier to understand, reuse, and change.
class ClassName: def __init__(self, attribute): self.attribute = attribute def method(self): # actions using self.attribute
class defines a new object type.
__init__ sets up the object when created.
class Dog: def __init__(self, name): self.name = name def bark(self): print(f"{self.name} says Woof!")
class Car: def __init__(self, color, speed): self.color = color self.speed = speed def drive(self): print(f"Driving at {self.speed} mph")
This program creates a Person object named Alice who is 30 years old, then says hello.
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.") p = Person("Alice", 30) p.greet()
Objects bundle data and actions, making code easier to manage.
Using classes helps avoid repeating code.
OOP fits well when you think about things as objects with properties and behaviors.
OOP groups related data and actions into objects.
It helps organize, reuse, and update code easily.
It models real-world things in programs clearly.
class Dog:
def __init__(self, name):
self.name = name
def speak(self):
return self.name + ' says Woof!'
my_dog = Dog('Buddy')
print(my_dog.speak())class Person:
def __init__(self, name):
name = name
def greet(self):
print('Hello, ' + self.name)