目录
Python类
Python类的设计原则
- 封装(Encapsulation):Python类被设计用来将相关数据和行为封装到一个独立的单元中。
- 继承(Inheritance):Python支持继承,允许子类从父类继承属性和方法。有利于代码的复用和创建相关类的层次结构。
- 多态(Polymorphism):Python支持多态,也就意味着不同类的对象可以被视为同一类型,这使得代码的设计具有更大的灵活性。
- 组合(Composition):Python鼓励使用组合而不是继承,这意味着对象是由其他对象组成的,而不是由父类派生的。这可以使您的代码更加模块化,更易于维护。
- Duck类型(Duck typing):Python使用Duck类型,这意味着对象的类型由其行为而非类决定,这样更容易编写可用于各种对象的通用代码。
- 特殊方法(Special methods):Python提供了许多特殊方法,允许为内置操作自定义行为。例如__len__方法允许你定义len()函数如何处理类的对象。
- 可读性(Readability):与Python的一般设计原则一样,类也应该优先考虑可读性和简单性,也就是说,对方法和属性使用清晰简洁的名称,避免不必要的复杂性。
特殊方法【Special methods】
Python中的特殊方法是一系列预定义的方法,允许你为对象上的内置操作定义自定义行为,使用双下划线前缀和后缀来识别,也成为"dunder"方法。这里讲述一些Python类中常用的特殊方法:
<ol>__init__(self, ...): 这是构造方法,对象创建时调用,用于初始化对象的属性并设置其初始状态。
__str__(self): 返回对象的字符串表示,用于创建一个人类可读的字符串表示。
__repr__(self): 返回对象的字符串表示,用于创建可用于创建对象的字符串表示。
__len__(self): 返回对象的长度,供len()函数使用。
__getitem__(self, key): 这个方法允许你以括号的形式访问对象的元素,可以使用[]来访问元素。
__setitem__(self, key, value): 这个方法允许你以括号的形式设置对象元素的值,可以使用[]来修改元素的值。
__delitem__(self, key): 这个方法允许你以括号的形式删除对象的元素。
__add__(self, other): 自定义对象的+操作方式。
__eq__(self, other): 自定义对象的==操作方式。
__lt__(self, other): 自定义对象的 other.agep1 = Person("Alice", 25)p2 = Person("Bob", 30)p3 = Person("Charlie", 20)people = [p1, p2, p3]print(p1) # Output: Person(name='Alice', age=25)print(min(people).name) # Output: 'Charlie'print(max(people).name) # Output: 'Bob'[/code]特殊方法与内置函数的对应:
特殊方法内置函数备注__len__()len()返回对象的长度__getitem__(), __setitem__()[]定义对象元素的访问和修改行为__iter__(), __next__()for等定义对象的迭代行为__contains__()in判断对象是否包含某个特定元素__add__(), __radd__()+定义对象的加法行为__sub__(), __rsub__()-定义对象的减法行为__mul__(), __rmul__()*定义对象的乘法行为__divmod__(), __rdivmod__()divmod()定义对象的余数除法行为__eq__(), __ne__()==, !=定义对象的判等操作__lt__(), __le__(),
__gt__(), __ge__()=定义对象间的比较操作__hash__()hash()定义对象的哈希值(hash value)English Version
The key design principles for Python classes
- Encapsulation:Python classes are designed to encapsulated related data and bahavior into a single unit.
- Inheritance:Python supports inheritance, which allows classes to inherit attributes and methods from parent classes. This makes it easier to reuse code and create hierarchies of related classes.
- Polymorphism:Python supports polymorphism, which means that objects of different classes can be treated as if they are the same type. This allows for greater flexibility in the design of your code.
- Composition:Python encourages the use of composition over inheritance, which means that objects are made up of other objects rather than being derived from parent classes. This can make your code more modular and easier to maintain.
- Duck typing: Python uses duck typing, which means that the type of an object is determined by its behavior rather than its class. This makes it easier to write generic code that works with a variety of objects.
- Special methods: Python has a number of special methods that allow you to define custom behavior for built-in operations. For example, the __len__ method allows you to define how the len() function works with objects of your class.
- Readability: As with the general design principles of Python, classes should also prioritize readability and simplicity. This means using clear and concise names for methods and attributes, avoiding unnecessary complexity, and following PEP 8 guidelines for formatting.
Special methods
Special methods in Python are a set of predefined methods that allow you to define custom behavior for built-in operations on your objects. They are identified by their double underscore prefix and suffix, also known as "dunder" methods.
Here are some of the most commonly used special methods in Python:
<ol>__init__(self, ...): This is the constructor method that is called when an object is called. It initializes the object's attributes and sets its initial state.
__str__(self): This methods returns a string representation of the object. It's called by the str() function and by the print() statement.
__repr__(self): This method returns a string representation of the object that can be used to recreate the object. It is called by the repr() function and by the interactive Python shell. The difference between __str__ and __repr__ is that __repr__ is used to create an unambiguous string representation of an object that can be used to recreate the object, while __str__ is used to create a human-readable string representation of an object.
__len__(self): This method returns the length of the object. It is called by the len() function.
__getitem__(self, key): This method allows you to access an item in the object using bracket notation. It is called when you use the bracket operation([]) on the object.
__setitem__(self, key, value): This method allows you to set the value of an item in the object using bracket notation. It is called when you use the bracket operation([]) on the object with an assignment.
__delitem__(self, key): This method allows you to delete an item from the object using bracket notation. It is called when you use the del statement on the object with bracket notation.
__add__(self, other): This method allows you to define how the + operator works with your object. It is called when you use the + operator on the object.
__eq__(self, other): This method allows you to define how the == operator works with your object. It is called when you use the == operator on the object.
__lt__(self, other): This method allows you to define how the |