Python面向对象
Python第十课,本文将讲述Python面向对象
pythonclass Student:
# 属性(成员变量)
name = None
age = None
# 行为(成员方法)
def study(self):
print(f"{self.name}正在学习")
# 创建对象
stu = Student()
stu.name = "张三"
stu.study()
pythondef introduce(self):
print(f"我叫{self.name},今年{self.age}岁")
__init__
pythondef __init__(self, name, age):
self.name = name
self.age = age
__
开头的变量/方法(实际是名称改写)pythonclass Phone:
__voltage = 3.7 # 私有变量
def __check_5g(self): # 私有方法
if self.__voltage > 3:
return True
def call(self): # 公有方法
if self.__check_5g():
print("5G通话已开启")
class 子类(父类)
class 子类(父类1, 父类2)
pythonclass AndroidPhone(Phone):
def __init__(self, brand):
super().__init__() # 调用父类构造
self.brand = brand
def call(self): # 方法重写
print(f"{self.brand}定制化通话界面")
super().call()
pythonfrom abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self):
pass
class Dog(Animal):
def sound(self):
return "汪汪"
class Cat(Animal):
def sound(self):
return "喵喵"
__str__
:定义对象字符串表示__eq__
:定义相等比较逻辑__lt__
:定义大小比较逻辑pythonclass Product:
def __init__(self, price):
self.price = price
def __str__(self):
return f"产品价格:{self.price}"
def __lt__(self, other):
return self.price < other.price
var: type
pythonfrom typing import Union
def process(data: Union[int, str]) -> list:
return [data] * 3
python# 数据基类
class BaseData:
def __init__(self, date, amount):
self.date = date
self.amount = amount
# 文件读取器(抽象类)
class FileReader:
def read(self, path) -> list[BaseData]:
raise NotImplementedError
# CSV实现
class CSVReader(FileReader):
def read(self, path):
# 解析CSV返回BaseData列表
pass
# 业务处理
class DataAnalyzer:
def __init__(self, reader: FileReader):
self.reader = reader
def daily_summary(self, path):
data = self.reader.read(path)
# 计算逻辑...
本文作者:Dageling003
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!