1 Star 0 Fork 0

巧克力ovo/PythonLearn

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
5-1.py 14.86 KB
一键复制 编辑 原始数据 按行查看 历史
wlt 提交于 1个月前 . 5
#面向过程:按步骤实现(蛋炒饭) 面向对象:按对象实现(盖浇饭) 封装(将数据和操作数据的方法绑定在一起,隐藏内部实现细节,只暴露必要的接口)、继承(通过继承机制,子类可以复用父类的属性和方法,同时可以扩展或重写父类的功能)、多态(不同的对象可以以相同的方式调用方法,但表现出不同的行为,从而提高代码的灵活性和可扩展性)
#类=属性(结构体)+方法(函数)
#类:是一个抽象的概念,表示一类事物的共同特征和行为
#__:private 私有属性和方法,只能在类的内部访问,不能在类的外部访问
#_:protected 受保护的属性和方法,可以在类的内部和子类中访问,但不能在类的外部访问
#方法属性:
class Person:
#构造函数:用于创建对象时初始化属性
#self:指向当前对象的引用,类似于C++中的this指针
#__init__:特殊方法,用于初始化对象的属性
#__init__方法在创建对象时自动调用
#__init__方法的参数包括self和其他属性参数
#self.name和self.age是实例属性,用于存储对象的状态
#各个属性不需要提前定义,直接在__init__方法中定义即可
def __init__(self, name, age):
self.name = name
self.age = age
#实例方法:用于定义对象的行为
def introduce(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
def celebrate_birthday(self):
self.age += 1 #修改实例属性
print(f"Happy birthday! I am now {self.age} years old.")
def __foo__(self):
#私有方法:只能在类的内部访问,不能在类的外部访问
print("This is a private method.")
def _foo_(self):
#受保护的方法:可以在类的内部和子类中访问,但不能在类的外部访问
print("This is a protected method.")
def _foo(self):
#公共方法:可以在类的内部和外部访问
print("This is a public method.")
def __str__(self):
#__str__方法用于定义对象的字符串表示形式
return f"Person(name={self.name}, age={self.age})"
def __repr__(self):
#__repr__方法用于定义对象的正式字符串表示形式
return f"Person(name={self.name}, age={self.age})"
def __len__(self):
#__len__方法用于定义对象的长度
return len(self.name)
def __getitem__(self, index):
#__getitem__方法用于定义对象的索引访问
return self.name[index]
def __setitem__(self, index, value):
#__setitem__方法用于定义对象的索引赋值
self.name[index] = value
def __delitem__(self, index):
#__delitem__方法用于定义对象的索引删除
del self.name[index]
def __iter__(self):
#__iter__方法用于定义对象的迭代器
return iter(self.name)
def __next__(self):
#__next__方法用于定义对象的迭代器的下一个元素
return next(self.name)
def __contains__(self, item):
#__contains__方法用于定义对象的成员测试
return item in self.name
def __call__(self, *args, **kwargs):
#__call__方法用于定义对象的可调用性
print(f"Calling {self.name} with arguments: {args} and keyword arguments: {kwargs}")
def __format__(self, format_spec):
#__format__方法用于定义对象的格式化输出
return f"{self.name} is {self.age} years old."
def __hash__(self):
#__hash__方法用于定义对象的哈希值
return hash((self.name, self.age))
def __eq__(self, other):
#__eq__方法用于定义对象的相等性比较
if isinstance(other, Person):
return self.name == other.name and self.age == other.age
return False
def __ne__(self, other):
#__ne__方法用于定义对象的不相等性比较
return not self.__eq__(other)
def __lt__(self, other):
#__lt__方法用于定义对象的小于比较
if isinstance(other, Person):
return self.age < other.age
return NotImplemented
def __le__(self, other):
#__le__方法用于定义对象的小于等于比较
if isinstance(other, Person):
return self.age <= other.age
return NotImplemented
def __gt__(self, other):
#__gt__方法用于定义对象的大于比较
if isinstance(other, Person):
return self.age > other.age
return NotImplemented
def __ge__(self, other):
#__ge__方法用于定义对象的大于等于比较
if isinstance(other, Person):
return self.age >= other.age
return NotImplemented
def __add__(self, other):
#__add__方法用于定义对象的加法运算
if isinstance(other, Person):
return Person(self.name + other.name, self.age + other.age)
return NotImplemented
def __sub__(self, other):
#__sub__方法用于定义对象的减法运算
if isinstance(other, Person):
return Person(self.name - other.name, self.age - other.age)
return NotImplemented
def __mul__(self, other):
#__mul__方法用于定义对象的乘法运算
if isinstance(other, Person):
return Person(self.name * other.name, self.age * other.age)
return NotImplemented
def __truediv__(self, other):
#__truediv__方法用于定义对象的除法运算
if isinstance(other, Person):
return Person(self.name / other.name, self.age / other.age)
return NotImplemented
def __floordiv__(self, other):
#__floordiv__方法用于定义对象的整除运算
if isinstance(other, Person):
return Person(self.name // other.name, self.age // other.age)
return NotImplemented
def __mod__(self, other):
#__mod__方法用于定义对象的取模运算
if isinstance(other, Person):
return Person(self.name % other.name, self.age % other.age)
return NotImplemented
def __pow__(self, other):
#__pow__方法用于定义对象的幂运算
if isinstance(other, Person):
return Person(self.name ** other.name, self.age ** other.age)
return NotImplemented
def __and__(self, other):
#__and__方法用于定义对象的与运算
if isinstance(other, Person):
return Person(self.name & other.name, self.age & other.age)
return NotImplemented
def __or__(self, other):
#__or__方法用于定义对象的或运算
if isinstance(other, Person):
return Person(self.name | other.name, self.age | other.age)
return NotImplemented
def __xor__(self, other):
#__xor__方法用于定义对象的异或运算
if isinstance(other, Person):
return Person(self.name ^ other.name, self.age ^ other.age)
return NotImplemented
def __invert__(self):
#__invert__方法用于定义对象的取反运算
return Person(~self.name, ~self.age)
def __reversed__(self):
#__reversed__方法用于定义对象的反向迭代
return reversed(self.name)
def __sizeof__(self):
#__sizeof__方法用于定义对象的大小
return len(self.name) + len(str(self.age))
def __del__(self):
#__del__方法用于定义对象的删除操作
print(f"Deleting {self.name}")
del self.name
del self.age
def __copy__(self):
#__copy__方法用于定义对象的浅拷贝
return Person(self.name, self.age)
def __deepcopy__(self, memo):
#__deepcopy__方法用于定义对象的深拷贝
#深拷贝会递归地复制对象及其引用的对象
#在深拷贝中,使用copy.deepcopy函数来复制对象的属性
#memo是一个字典,用于存储已经复制的对象,以避免循环引用
from copy import deepcopy
return Person(deepcopy(self.name, memo), deepcopy(self.age, memo))
def __enter__(self):
#__enter__方法用于定义对象的上下文管理器的进入操作
print(f"Entering context with {self.name}")
return self
def __exit__(self, exc_type, exc_value, traceback):
#__exit__方法用于定义对象的上下文管理器的退出操作
print(f"Exiting context with {self.name}")
return False
def __getattr__(self, name):
#__getattr__方法用于定义对象的属性访问
if name == "age":
return self.age
raise AttributeError(f"{name} not found")
def __setattr__(self, name, value):
#__setattr__方法用于定义对象的属性赋值
if name == "age":
if value < 0:
raise ValueError("Age cannot be negative")
super().__setattr__(name, value)
def __delattr__(self, name):
#__delattr__方法用于定义对象的属性删除
if name == "age":
raise AttributeError("Cannot delete age")
super().__delattr__(name)
def __dir__(self):
#__dir__方法用于定义对象的属性和方法列表
return ["name", "age", "introduce", "celebrate_birthday"]
def __getstate__(self):
#__getstate__方法用于定义对象的序列化状态
return {"name": self.name, "age": self.age}
def __setstate__(self, state):
#__setstate__方法用于定义对象的反序列化状态
self.name = state["name"]
self.age = state["age"]
def __reduce__(self):
#__reduce__方法用于定义对象的序列化和反序列化
return (self.__class__, (self.name, self.age))
def __reduce_ex__(self, protocol):
#__reduce_ex__方法用于定义对象的序列化和反序列化
#protocol是协议版本号,通常为0或1
#协议版本号决定了序列化的方式和格式
#在这里,我们使用__class__和__dict__来序列化对象的状态
#__class__表示对象的类,__dict__表示对象的属性字典
#返回一个元组,包含类、初始化参数和属性字典
#这个元组将用于反序列化时创建对象
#在反序列化时,Python会调用__class__来创建对象,并使用初始化参数和属性字典来初始化对象的状态
return (self.__class__, (self.name, self.age), self.__dict__)
def __doc__(self):
#__doc__方法用于定义对象的文档字符串
return "This is a Person class."
def __annotations__(self):
#__annotations__方法用于定义对象的类型注解
return {"name": str, "age": int}
def __class__(self):
#__class__方法用于定义对象的类
return Person
def __module__(self):
#__module__方法用于定义对象的模块
return __name__
def __package__(self):
#__package__方法用于定义对象的包
return __package__
def __subclasshook__(self, subclass):
#__subclasshook__方法用于定义对象的子类钩子
#这个方法用于检查一个类是否是另一个类的子类
#通常在元类中使用,用于实现抽象基类的功能
#在这里,我们返回NotImplemented,表示不支持子类钩子
return NotImplemented
def __mro__(self):
#__mro__方法用于定义对象的类层次结构
#这个方法返回一个元组,包含类及其父类的顺序
#在这里,我们返回一个包含Person类及其父类的元组
return (Person, object)
def __subclasses__(self):
#subclasses__方法用于定义对象的子类列表
#这个方法返回一个列表,包含所有的子类
#在这里,我们返回一个空列表,表示没有子类
return []
def __subclasscheck__(self, subclass):
#subclasscheck__方法用于定义对象的子类检查
#这个方法用于检查一个类是否是另一个类的子类
#在这里,我们返回False,表示不是子类
return False
def __instancecheck__(self, instance):
#instancecheck__方法用于定义对象的实例检查
#这个方法用于检查一个对象是否是另一个类的实例
#在这里,我们返回False,表示不是实例
return False
def __classcheck__(self, cls):
#classcheck__方法用于定义对象的类检查
#这个方法用于检查一个类是否是另一个类的类
#在这里,我们返回False,表示不是类
return False
def __init_subclass__(cls):
#__init_subclass__方法用于定义对象的子类初始化
#这个方法在创建子类时自动调用
#在这里,我们返回None,表示不需要初始化
return None
def __init_subclass__(cls, **kwargs):
#__init_subclass__方法用于定义对象的子类初始化
#这个方法在创建子类时自动调用
#在这里,我们返回None,表示不需要初始化
return None
def __init_subclass__(cls, **kwargs):
#__init_subclass__方法用于定义对象的子类初始化
#这个方法在创建子类时自动调用
#在这里,我们返回None,表示不需要初始化
return None
def __new__(cls):
#__new__方法用于定义对象的创建
#这个方法在创建对象时自动调用
#在这里,我们返回一个新的Person对象
return super().__new__(cls)
def __new__(cls, *args, **kwargs):
#__new__方法用于定义对象的创建
#这个方法在创建对象时自动调用
#在这里,我们返回一个新的Person对象
return super().__new__(cls)
def __ror__(self, value):
#__ror__方法用于定义对象的右操作数
#这个方法在使用|运算符时自动调用
#在这里,我们返回一个新的Person对象
return Person(self.name | value, self.age | value)
def __radd__(self, other):
#__radd__方法用于定义对象的右加法运算
#这个方法在使用+运算符时自动调用
#在这里,我们返回一个新的Person对象
return Person(self.name + other.name, self.age + other.age)
def __rsub__(self, other):
#__rsub__方法用于定义对象的右减法运算
#这个方法在使用-运算符时自动调用
#在这里,我们返回一个新的Person对象
return Person(self.name - other.name, self.age - other.age)
def __rmul__(self, other):
#__rmul__方法用于定义对象的右乘法运算
#这个方法在使用*运算符时自动调用
#在这里,我们返回一个新的Person对象
return Person(self.name * other.name, self.age * other.age)
def main():
#创建对象
person1 = Person("Alice", 25)
#调用方法
person1.introduce()
person1.celebrate_birthday()
if __name__ == "__main__":
main()
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/chocolate-ovo/python-learn.git
git@gitee.com:chocolate-ovo/python-learn.git
chocolate-ovo
python-learn
PythonLearn
master

搜索帮助