Introduction
Classes help you create your own blueprints for things. Objects are the actual things made from those blueprints.
Jump into concepts and practice - no test required
Classes help you create your own blueprints for things. Objects are the actual things made from those blueprints.
class ClassName: def __init__(self, parameters): self.attribute = value def method(self): # code here # Create an object obj = ClassName(arguments)
class defines a new blueprint.
__init__ is a special method that runs when you make a new object.
class Dog: def __init__(self, name): self.name = name def bark(self): print(f"{self.name} says Woof!") my_dog = Dog("Buddy") my_dog.bark()
class Car: def __init__(self, color, speed): self.color = color self.speed = speed def drive(self): print(f"Driving at {self.speed} km/h") car1 = Car("red", 100) car1.drive()
This program creates a Person named Alice who is 30 years old and 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.") person1 = Person("Alice", 30) person1.greet()
Use self to refer to the current object inside methods.
You can create many objects from one class, each with its own data.
Classes help keep your code organized and easy to understand.
Classes are blueprints for creating objects.
Objects hold data and can do actions defined by their class.
Use classes to model real-world things and organize your code.
class in Python?Car in Python?class followed by the class name and parentheses.class Car(): which is correct syntax. Others use wrong keywords or formats.class Dog():
def __init__(self, name):
self.name = name
def bark(self):
return f"{self.name} says Woof!"
my_dog = Dog("Buddy")
print(my_dog.bark())__init__ method sets the name attribute to "Buddy" when my_dog is created.bark method returns a string using the dog's name, so it returns "Buddy says Woof!".class Person():
def __init__(self, name):
name = name
p = Person("Alice")
print(p.name)name = name, which only changes the local variable, not the object's attribute.self.name = name to store the value in the object for later access.BankAccount that stores an account holder's name and balance. It should have a method deposit(amount) that adds money to the balance only if the amount is positive. Which code correctly implements this?self.name and self.balance with a default balance of 0.amount to self.balance only if amount > 0, which matches the requirement.