简体   繁体   English

如何在python中重用功能代码

[英]How to reuse function codes in python

I have a basic function with following codes: 我有以下代码的基本功能:

def func_0():
    codes_segment_a
    codes_segment_b
    codes_segment_c

Many other small functions share the codes with the func_0, but many add some new codes. 许多其他小功能与func_0共享代码,但是许多小功能添加了一些新代码。 Take the following function as an example: 以以下功能为例:

def func_x():
    new codes...
    codes_segment_a
    codes_segment_b
    new codes...
    codes_segment_c

The simpliest and most tedicous solution I figure out is to copy and paste the shared codes. 我发现最简单,最繁琐的解决方案是复制并粘贴共享代码。 But it looks so stupid because I have more then 20 such functions. 但这看起来很愚蠢,因为我有20多个这样的功能。

I am quit new in python and please give me some suggestions. 我在python中退出了,请给我一些建议。 Detailed explaination or examples are quite preferred. 详细的解释或示例是比较可取的。 Thanks. 谢谢。

One general approach is to use classes and inheritance. 一种通用方法是使用类和继承。 A super-simplified example (but see Classes for how to use classes and inheritance properly): 一个超级简化的示例(有关正确使用类和继承的信息,请参见 ):

class Reuse(object):
    def square(self, x):
        return x**2

class Specific(Reuse):
    def times3(self,x):
        return x*3

sp = Specific()
print(sp.times3(4))

12 12

print(sp.square(4))

16 16

If you put utility functions in a "top-level" class, and then make new classes that inherit from that one but that contain the specific functions you want, then you only need to make the utility functions once. 如果将实用程序功能放在“顶级”类中,然后创建从该类继承但包含所需特定功能的新类,则只需制作一次实用程序功能。 There's nothing wrong with making very short functions, even 3-4 lines long, because it can improve readability and efficiency. 制作非常短的功能(甚至是3-4行)没有什么错,因为它可以提高可读性和效率。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM