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

相关推荐
He1955019 分钟前
Go初级之十:错误处理与程序健壮性
开发语言·python·golang
m0_7381207233 分钟前
CTFshow系列——PHP特性Web93-96
开发语言·安全·web安全·php·ctfshow
m0_5704664144 分钟前
代码随想录算法训练营第二十八天 | 买卖股票的最佳实际、跳跃游戏、K次取反后最大化的数组和
java·开发语言·算法
程序喵大人44 分钟前
分享个C++线程池的实现源码
开发语言·c++·线程池
和鲸社区1 小时前
《斯坦福CS336》作业1开源,从0手搓大模型|代码复现+免环境配置
人工智能·python·深度学习·计算机视觉·语言模型·自然语言处理·nlp
不会吃萝卜的兔子1 小时前
go webrtc - 1 go基本概念
开发语言·golang·webrtc
豌豆花下猫1 小时前
Python 潮流周刊#118:Python 异步为何不够流行?(摘要)
后端·python·ai
THMAIL1 小时前
深度学习从入门到精通 - LSTM与GRU深度剖析:破解长序列记忆遗忘困境
人工智能·python·深度学习·算法·机器学习·逻辑回归·lstm
要做朋鱼燕2 小时前
【C++】 priority_queue 容器模拟实现解析
开发语言·c++·笔记·职场和发展
jiaway2 小时前
【C语言】第四课 指针与内存管理
c语言·开发语言·算法