如何组织我的 Python 代码

编写代码更像是一门艺术,而不是一门科学。编写精炼、合乎逻辑且强大的工程解决方案对于解决问题非常重要。然而,似乎存在一个重大挑战:让这些解决方案全面且易读。

本文的重点是如何最好地组织 Python 类,使其既可读又整洁。Python 在方法组织方面没有严格的规定;例如,如果您决定将方法放在__init__类的末尾或放在最前面,您不会受到惩罚。但是,遵守广泛接受的惯例不仅可以使协作更容易,还可以促进更好的文档。

定义函数方法的顺序

  1. 魔法方法
  2. 私有方法
  3. 公共方法
  4. 辅助方法

1.魔法方法

简单来说,在python中,任何以__开头和结尾的函数,都是魔法函数,例如:__init__就是一种魔法函数。

它可以重载默认函数的行为,特殊方法以两个下划线开始,两个下划线结尾。于是乎特殊方法也叫双下方法(dunder method)。dunder,即double的d+underline 的

例子:

python 复制代码
class ClassWithMagicMethod:
    """Example class"""

    def __new__(self):
        pass

    def __init__(self, value: int):
        """This is the init method"""
        self.value =value

    def __str__(self):
        return str(self.value)

    def __repr__(self):
        return f"<ExampleClass({self.value})>"

注意到__new__方法在方法之前吗__init__?这样做是最佳做法,可确保代码库流程正确且合乎逻辑。

2.私有方法

私有方法供类内部使用。这些方法通常以下划线 (__) 开头,应放在魔法方法之后。将私有方法组织在一起有助于保持类的内部机制与公共接口之间的明确区分。

例子:

python 复制代码
class ClassWithPrivateMethod:
    # magic methods goes here...
    def __private_method(self):
        # This is a private method
        print("this is private method")
尝试访问__private_method类外部将会引发此错误:
c = ClassWithPrivateMethod()
c.__private_method()

--------------output-----------
ERROR!
Traceback (most recent call last):
  File "<main.py>", line 12, in <module>
AttributeError: 'ClassWithPrivateMethod' object has no attribute '__private_method'

但是,可以在类中访问它:

python 复制代码
class ClassWithPrivateMethod:
    # magic methods goes here...
    def __private_method(self):
        # This is a private method
        print("this is private method")

    def another_method(self):
        """Method that accesses the private method"""
        self.__private_method()


c = ClassWithPrivateMethod()
c.another_method()
------------output----------
this is private method

尽管此方法被视为私有方法,但 Python 仍然可以通过使用以下语法创建辅助方法来访问它:f"_{class .name}__{<method_name>}"。现在可以正常工作。

python 复制代码
c = ClassWithPrivateMethod()
c._ClassWithPrivateMethod__private_method()
-------------output---------------
this is private method

您会注意到 Python 创建了一个辅助方法来访问私有方法;建议了如何使用或访问该方法的语法或模式。

3.公共方法

公共方法构成了类的主要接口。这些方法应该定义明确且记录良好,因为它们旨在供其他类或模块使用。保持公共方法井然有序并与私有方法区分开来可提高可读性和可用性。

例子:

python 复制代码
class ClassWithPublicMethod:
    # magic methods go here...
    # private methods next...

    def public_method(self):
        # This is a public method
        return self.value

4. 公共方法的辅助方法

辅助方法或支持方法可帮助公共方法执行其任务,应在其支持的公共方法之后立即定义。这些方法通常将复杂的任务分解为更简单、更易于管理的部分,从而提高代码的可重用性和清晰度。

例子:

python 复制代码
class ClassWithHelperMethod:
    # All previous methods here...

    def public_method(self):
        # This is a public method
        return self._helper_method()

    def _helper_method(self):
        # This is a helper method for the public method
        return self.value * 2

    def public_method_2(self):
         """This is another method"""
        pass

结论

通过按照建议的顺序组织方法(魔术方法、私有方法、公共方法和辅助方法),您可以为 Python 类创建清晰易读的结构。这种方法不仅有助于更轻松地进行协作和维护,还有助于创建其他人可以理解和有效使用的文档齐全的代码库。如果您在组织中工作,这也会改善入职体验。请记住,干净的代码不仅仅是让它工作;而是让它从长远来看易于理解和维护。

相关推荐
databook8 小时前
Manim实现闪光轨迹特效
后端·python·动效
Juchecar9 小时前
解惑:NumPy 中 ndarray.ndim 到底是什么?
python
用户8356290780519 小时前
Python 删除 Excel 工作表中的空白行列
后端·python
Json_9 小时前
使用python-fastApi框架开发一个学校宿舍管理系统-前后端分离项目
后端·python·fastapi
数据智能老司机16 小时前
精通 Python 设计模式——分布式系统模式
python·设计模式·架构
数据智能老司机17 小时前
精通 Python 设计模式——并发与异步模式
python·设计模式·编程语言
数据智能老司机17 小时前
精通 Python 设计模式——测试模式
python·设计模式·架构
数据智能老司机17 小时前
精通 Python 设计模式——性能模式
python·设计模式·架构
c8i17 小时前
drf初步梳理
python·django
每日AI新事件17 小时前
python的异步函数
python