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

相关推荐
Wzx1980122 分钟前
go基础语法练习
开发语言·后端·golang
忧郁的蛋~22 分钟前
.NET异步编程中内存泄漏的终极解决方案
开发语言·前端·javascript·.net
2301_7951672027 分钟前
玩转Rust高级应用. ToOwned trait 提供的是一种更“泛化”的Clone 的功能,Clone一般是从&T类型变量创造一个新的T类型变量
开发语言·后端·rust
你才是向阳花40 分钟前
如何用Python实现飞机大战小游戏
开发语言·python·pygame
合作小小程序员小小店1 小时前
web网页开发,在线%商城,电商,商品购买%系统demo,基于vscode,apache,html,css,jquery,php,mysql数据库
开发语言·前端·数据库·mysql·html·php·电商
草莓熊Lotso1 小时前
C++ 方向 Web 自动化测试实战:以博客系统为例,从用例到报告全流程解析
前端·网络·c++·人工智能·后端·python·功能测试
星释1 小时前
Rust 练习册 :Phone Number与电话号码处理
开发语言·机器学习·rust
one year.1 小时前
Linux:线程同步与互斥
java·开发语言
一 乐1 小时前
旅游|内蒙古景点旅游|基于Springboot+Vue的内蒙古景点旅游管理系统设计与实现(源码+数据库+文档)
开发语言·前端·数据库·vue.js·spring boot·后端·旅游
不爱编程的小九九1 小时前
小九源码-springboot103-踏雪阁民宿订购平台
java·开发语言·spring boot