目前什么编码做网站最好,网站建设的辅助软件,关键词批量调词 软件,做视频网站需要多少上传面向对象编程#xff08;OOP#xff09;是一种以对象为核心的编程范式。Python全面支持OOP#xff0c;主要包含以下核心概念#xff1a;一、类与对象1.类(Class)类是创建对象的模板或蓝图#xff0c;它定义了对象的属性和方法。class Dog:# 类属性#xff08;所有实例共享… 面向对象编程OOP是一种以对象为核心的编程范式。Python全面支持OOP主要包含以下核心概念一、类与对象1.类(Class)类是创建对象的模板或蓝图它定义了对象的属性和方法。
class Dog:# 类属性所有实例共享species Canis familiaris# 初始化方法构造对象def __init__(self, name, age):# 实例属性每个对象独立self.name nameself.age age# 实例方法def bark(self):return f{self.name} says Woof!2.对象Object对象是类的实例具有类定义的属性和方法。
my_dog Dog(Buddy, 3)
print(my_dog.bark()) # 输出: Buddy says Woof!二、三大核心特性1.封装Encapsulation 封装是将数据属性和操作数据的方法行为绑定在一起并隐藏内部实现细节只对外提供必要的接口。Python通过私有属性和私有方法实现封装。
class BankAccount:def __init__(self, balance0):self.__balance balance # 私有属性def deposit(self, amount):if amount 0:self.__balance amountreturn Truereturn Falsedef withdraw(self, amount):if 0 amount self.__balance:self.__balance - amountreturn Truereturn Falsedef get_balance(self): # 提供获取余额的方法return self.__balanceaccount BankAccount(100)
account.deposit(50)
print(account.get_balance()) # 输出: 150
# print(account.__balance) # 报错无法直接访问私有属性2.继承Inheritance继承允许一个类子类继承另一个类父类的属性和方法实现代码的重用和扩展。
class Animal:def __init__(self, name):self.name namedef speak(self):raise NotImplementedError(Subclass must implement abstract method)class Dog(Animal):def speak(self):return f{self.name} says woof!class Cat(Animal):def speak(self):return f{self.name} says meow!dog Dog(Buddy)
cat Cat(Whiskers)
print(dog.speak()) # 输出: Buddy says woof!
print(cat.speak()) # 输出: Whiskers says meow!3.多态Polymorphism 多态是指同一个方法调用在不同对象上产生不同的行为。在Python中多态通过继承和方法重写实现。
# 继续使用上面的Animal、Dog和Cat类def animal_sound(animal):print(animal.speak())animals [Dog(Buddy), Cat(Whiskers)]
for animal in animals:animal_sound(animal) # 分别输出: Buddy says woof! 和 Whiskers says meow!三、类成员详解 类成员是面向对象编程的核心概念Python中的类成员主要分为三类属性、方法和特殊成员。下面详细解析各类成员的特性和用法1.属性Attributes类型定义方式访问方式特点示例实例属性self.attr valueobj.attr每个对象独立self.name Alice类属性类内部直接定义Class.attr所有实例共享species Human保护属性_attr单下划线前缀obj._attr约定私有可访问self._id 123私有属性__attr双下划线前缀obj._Class__attr名称修饰强私有self.__password *** (1).类属性类属性是属于类的所有对象共享该属性。
class Circle:# 类属性pi 3.14159def __init__(self, radius):self.radius radiusdef area(self):return Circle.pi * self.radius ** 2circle1 Circle(5)
circle2 Circle(10)print(circle1.area()) # 输出: 78.53975
print(circle2.area()) # 输出: 314.159(2).实例属性实例属性是属于对象的每个对象可以有不同的属性值。
class Dog:def __init__(self, name, breed):# 实例属性self.name nameself.breed breeddog1 Dog(Buddy, Golden Retriever)
dog2 Dog(Max, German Shepherd)print(dog1.name) # 输出: Buddy
print(dog2.breed) # 输出: German Shepherd 综合案例
class User:# 类属性所有用户共享platform WebAppdef __init__(self, name):# 实例属性每个用户独立self.name name# 保护属性约定私有self._session_id id(self)# 私有属性强私有self.__password default# 访问示例
u User(Alice)
print(u.platform) # 类属性 → WebApp
print(u.name) # 实例属性 → Alice
print(u._session_id) # 保护属性 → 123456
print(u.__password) # 报错AttributeError
print(u._User__password) # 私有属性 → default不推荐2.方法Methods类型定义方式调用方式特点参数要求实例方法def method(self, ...):obj.method()可访问实例/类属性必须包含self类方法classmethodClass.method()操作类属性创建工厂方法必须包含cls静态方法staticmethodClass.method()功能独立无状态依赖无特殊参数(1). 实例方法实例方法是属于对象的方法第一个参数通常是 self用于引用对象本身。
class Rectangle:def __init__(self, length, width):self.length lengthself.width width# 实例方法def area(self):return self.length * self.widthrect Rectangle(5, 10)
print(rect.area()) # 输出: 50(2).类方法 类方法是属于类的方法使用 classmethod 装饰器定义第一个参数通常是 cls用于引用类本身。
class Pizza:def __init__(self, radius, ingredients):self.radius radiusself.ingredients ingredientsclassmethoddef margherita(cls):return cls(12, [tomato sauce, mozzarella, basil])classmethoddef pepperoni(cls):return cls(14, [tomato sauce, mozzarella, pepperoni])pizza1 Pizza.margherita()
pizza2 Pizza.pepperoni()print(pizza1.ingredients) # 输出: [tomato sauce, mozzarella, basil]
print(pizza2.radius) # 输出: 14(3).静态方法静态方法是属于类的方法使用 staticmethod 装饰器定义不需要 self 或 cls 参数。
class Math:staticmethoddef add(a, b):return a bresult Math.add(3, 5)
print(result) # 输出: 8综合案例:
class Calculator:# 类属性PI 3.14159# 实例方法def add(self, a, b):return a b# 类方法classmethoddef circle_area(cls, radius):return cls.PI * radius ** 2# 静态方法staticmethoddef is_even(num):return num % 2 0# 调用示例
calc Calculator()
calc.add(2, 3) # 实例方法 → 5
Calculator.circle_area(2) # 类方法 → 12.56636
Calculator.is_even(7) # 静态方法 → False3.特殊成员魔术方法 魔术方法Magic Methods是 Python 面向对象编程的核心特性它们以双下划线开头和结尾如 __init__用于定义类的特殊行为。这些方法会在特定操作发生时自动调用让自定义类拥有类似内置类型的行为。类别常用方法触发场景对象生命周期__new__, __init__, __del__创建、初始化、销毁对象字符串表示__str__, __repr__, __format__print(), str(), format()运算符重载__add__, __sub__, __mul__, __eq__, __lt__ 等, -, *, , 等操作容器行为__len__, __getitem__, __setitem__, __contains__, __iter__len(), [], in, for循环属性访问__getattr__, __getattribute__, __setattr__, __delattr__属性访问、设置、删除可调用对象__call__obj() 函数式调用上下文管理__enter__, __exit__with 语句数值转换__int__, __float__, __bool__int(), float(), bool()1. 对象生命周期方法
class Lifecycle:def __new__(cls, *args, **kwargs):print(创建对象内存分配)return super().__new__(cls)def __init__(self, name):print(f初始化对象: {name})self.name namedef __del__(self):print(f销毁对象: {self.name})obj Lifecycle(Test) # 输出: 创建对象 → 初始化对象: Test
del obj # 输出: 销毁对象: Test2. 字符串表示方法
class Person:def __init__(self, name, age):self.name nameself.age age# 用户友好展示def __str__(self):return f{self.name} ({self.age}岁)# 开发者调试/重建对象def __repr__(self):return fPerson({self.name}, {self.age})# 格式化输出def __format__(self, format_spec):if format_spec short:return self.name[0].upper()return str(self)p Person(张三, 30)
print(str(p)) # 张三 (30岁)
print(repr(p)) # Person(张三, 30)
print(f{p:short}) # 张 其他不在一一展示
class Vector2D:def __init__(self, x, y):self.x xself.y y# 字符串表示用户友好def __str__(self):return f({self.x}, {self.y})# 运算符重载向量加法def __add__(self, other):return Vector2D(self.x other.x, self.y other.y)# 长度定义模长def __len__(self):return int((self.x**2 self.y**2)**0.5)v1 Vector2D(3, 4)
v2 Vector2D(1, 2)
print(v1) # 触发__str__ → (3, 4)
print(v1 v2) # 触发__add__ → (4, 6)
print(len(v1)) # 触发__len__ → 5四、高级特性1.属性访问控制property装饰器实现属性保护
class Temperature:def __init__(self, celsius):self._celsius celsius # 保护属性propertydef celsius(self): # Getterreturn self._celsiuscelsius.setterdef celsius(self, value):if value -273.15:raise ValueError(Too cold)self._celsius value2.抽象基类ABC定义接口规范
from abc import ABC, abstractmethodclass Animal(ABC):abstractmethoddef speak(self):passclass Cat(Animal):def speak(self): # 必须实现抽象方法return Meow