Python Objects and Classes
class Person:
pass
p1 = Person()
print(p1)class Person:
name = "Alice"
age = 25
p = Person()
print(p.name)
print(p.age)Last updated
class Person:
pass
p1 = Person()
print(p1)class Person:
name = "Alice"
age = 25
p = Person()
print(p.name)
print(p.age)Last updated
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p = Person("Bob", 30)
print(p.name, p.age)class Person:
def __init__(self, name):
self.name = name
def greet(self):
return f"Hello, my name is {self.name}"
p = Person("Alice")
print(p.greet())class Student:
school = "Global Academy" # Class variable
def __init__(self, name):
self.name = name # Instance variable
s1 = Student("Alice")
s2 = Student("Bob")
print(s1.school)
print(s2.school)class Car:
def __init__(self, brand):
self.brand = brand
c1 = Car("Toyota")
c2 = Car("Tesla")
print(c1.brand)
print(c2.brand)class Employee:
def __init__(self, name):
self.name = name
emp = Employee("John")
emp.name = "Michael"
print(emp.name)class Product:
def __init__(self, price):
self.price = price
item = Product(100)
del item.price
# del item # Deletes the object entirelyclass User:
pass
user = User()
print(isinstance(user, User)) # True
print(type(user)) # <class '__main__.User'>class BankAccount:
def __init__(self, owner, balance):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
self.balance -= amount
account = BankAccount("Alice", 1000)
account.deposit(500)
print(account.balance) # Output: 1500