如何组织我的 Python 代码

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

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

定义函数方法的顺序

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

1.魔法方法

简单来说,在python中,任何以__开头和结尾的函数,都是魔法函数,例如:__init__就是一种魔法函数。
它可以重载默认函数的行为,特殊方法以两个下划线开始,两个下划线结尾。于是乎特殊方法也叫双下方法(dunder method)。dunder,即double的d+underline 的
例子:

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.私有方法

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

例子:

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'

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

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>}"。现在可以正常工作。

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

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

3.公共方法

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

例子:

class ClassWithPublicMethod:
    # magic methods go here...
    # private methods next...

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

4. 公共方法的辅助方法

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

例子:

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

  • 20
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值