小编Tim*_*Lin的帖子

同一个类中的同名函数,优雅的方式来确定调用哪个?

我试图在Python脚本中进行产品版本控制有一个特定的原因,但我无法弄清楚如何以优雅的方式做到这一点 - 请帮忙.

目前我正在做类似下面的事情.但是,在更改版本内容时,脚本很难维护.

class Product(object):

    def __init__(client):
        self.version = client.version  # get client version from another module

    def function():
        if self.version == '1.0':
            print('for version 1.0')
        elif self.version == '2.0':
            print('for version 2.0')
        else:
            print(f'function not support {self.version}')
Run Code Online (Sandbox Code Playgroud)

因此,我想做类似下面的事情来分离具有相同名称的功能.

class Product(object):

    def __init__(client):
        self.version = client.version  # get client version from another module

    def function():
        print('for version 1.0')

    def function():
        print('for version 2.0')
Run Code Online (Sandbox Code Playgroud)

我正在考虑使用装饰器来实现这个目的:

class Product(object):

    def __init__(client):
        self.version = client.version  # get client version from another …
Run Code Online (Sandbox Code Playgroud)

python version-control python-decorators python-3.6

35
推荐指数
4
解决办法
3406
查看次数