Py-OOP-Cheatsheet
发布于 • 作者: Ethan
# ===========================
# Python OOP Cheat Sheet
# ===========================
# ---------------------------
# 1. Class & Object
# ---------------------------
# Define a class
class Person:
species = "Homo sapiens" # Class variable (shared by all instances)
# Constructor (initializer)
def __init__(self, name, age):
self.name = name # Instance variable
self.age = age
# Instance method
def greet(self):
print(f"Hello, my name is {self.name} and I'm {self.age} years old.")
# Class method (decorated with @classmethod)
@classmethod
def species_info(cls):
print(f"Species: {cls.species}")
# Static method (independent of class or instance)
@staticmethod
def is_adult(age):
return age >= 18
# Create object
p1 = Person("Han", 22)
p1.greet()
Person.species_info()
print(Person.is_adult(20))
# ---------------------------
# 2. Encapsulation
# ---------------------------
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private attribute (double underscore)
def deposit(self, amount):
self.__balance += amount
def withdraw(self, amount):
if amount <= self.__balance:
self.__balance -= amount
else:
print("Insufficient funds.")
def get_balance(self):
return self.__balance
acct = BankAccount(1000)
acct.deposit(500)
print(acct.get_balance()) # 1500
# ---------------------------
# 3. Inheritance
# ---------------------------
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print("Some generic sound")
# Subclass inherits from parent class
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name) # Call parent constructor
self.breed = breed
# Method overriding
def speak(self):
print(f"{self.name} says Woof!")
dog = Dog("Buddy", "Golden Retriever")
dog.speak()
# ---------------------------
# 4. Polymorphism
# ---------------------------
class Cat(Animal):
def speak(self):
print(f"{self.name} says Meow!")
animals = [Dog("Fido", "Labrador"), Cat("Whiskers")]
for a in animals:
a.speak() # Calls different methods depending on object type
# ---------------------------
# 5. Abstract Class
# ---------------------------
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
circle = Circle(5)
print(circle.area())
# ---------------------------
# 6. Property Decorator
# ---------------------------
class Student:
def __init__(self, name):
self._name = name
@property
def name(self):
print("Getting name...")
return self._name
@name.setter
def name(self, value):
print("Setting name...")
self._name = value
s = Student("Han")
print(s.name)
s.name = "Han Li"
# ---------------------------
# 7. Magic / Dunder Methods
# ---------------------------
class Vector:
def __init__(self, x, y):
self.x, self.y = x, y
def __repr__(self):
return f"Vector({self.x}, {self.y})"
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __eq__(self, other):
return self.x == other.x and self.y == other.y
v1 = Vector(1, 2)
v2 = Vector(3, 4)
print(v1 + v2) # Vector(4, 6)
print(v1 == Vector(1, 2)) # True
# ---------------------------
# 8. Composition
# ---------------------------
class Engine:
def start(self):
print("Engine starting...")
class Car:
def __init__(self):
self.engine = Engine() # Contains an Engine object (composition)
def start(self):
self.engine.start()
print("Car is running.")
car = Car()
car.start()
# ---------------------------
# 9. Class Relationship Checks
# ---------------------------
print(isinstance(dog, Dog)) # True
print(isinstance(dog, Animal)) # True
print(issubclass(Dog, Animal)) # True
# ---------------------------
# 10. Data Class (@dataclass)
# ---------------------------
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
p = Point(3, 4)
print(p)