如何组织我的 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 类创建清晰易读的结构。这种方法不仅有助于更轻松地进行协作和维护,还有助于创建其他人可以理解和有效使用的文档齐全的代码库。如果您在组织中工作,这也会改善入职体验。请记住,干净的代码不仅仅是让它工作;而是让它从长远来看易于理解和维护。

相关推荐
rising start4 分钟前
二、python面向对象高级
开发语言·python
虎头金猫4 分钟前
随时随地处理图片文档!Reubah 加cpolar的实用体验
linux·运维·人工智能·python·docker·开源·visual studio
Yue丶越5 分钟前
【Python】基础语法入门(二)
android·开发语言·python
Demon--hx7 分钟前
[c++]string的三种遍历方式
开发语言·c++·算法
共享家952720 分钟前
QT-系统(多线程)
开发语言·数据库·qt
郝学胜-神的一滴1 小时前
Effective Python 第52条:用subprocess模块优雅管理子进程
linux·服务器·开发语言·python
valan liya1 小时前
C++list
开发语言·数据结构·c++·list
Le1Yu1 小时前
订单取消功能(退款功能、策略模式、定时任务)
开发语言
章鱼哥7301 小时前
Java 策略模式 + 聚合对象:实现多模块的统计与聚合,快速扩展的实战
java·开发语言·策略模式
是店小二呀1 小时前
openGauss进阶:使用DBeaver可视化管理与实战
开发语言·人工智能·yolo