簡體   English   中英

方法內的默認參數

[英]Default argument inside method

我嘗試為 class 實現格式。我想要一個默認為“短”的參數。

我試過:

def __format__(self, code='short'):
    if code == 'short':
        return f'Filename {self.filename}: {self.config}'
    elif code == 'long':
        string = f'{self.filename}'
        for key, value in self.config.items():
           string = string + f'\n{key}{self.sep}{value}'
        return string
    else:
        raise TypeError('Choose between short or long.')

my_config_file = ConfigFileWithBackups('mycofig.txt')
print(f'{my_config_file}')

最后一次調用引發了 TypeError,但我希望默認為“短”實現。 任何想法為什么?

當然我可以使用類似的東西:if not code or code == 'short' 但我希望我能理解我最初的實現是怎么回事。

__format__ 方法將使用 format_spec 調用,在您的情況下,它將是一個空字符串。 將始終傳遞一個值。 因此,設置默認值是沒有意義的。 您是否意識到您可以這樣做:- print(f'{my_config_file:short}')或者如果 format_spec 是一個空字符串,則假設它等同於 'short'

class ConfigFileWithBackups:
    def __init__(self, filename):
        self.filename = filename
        self.config = {}
        self.sep = ':'
    def __format__(self, format_spec):
        match format_spec:
            case '' | 'short':
                return f'Filename {self.filename}: {self.config}'
            case 'long':
                string = f'{self.filename}'
                for key, value in self.config.items():
                    string = string + f'\n{key}{self.sep}{value}'
                return string
        raise TypeError('Choose between short or long.')

my_config_file = ConfigFileWithBackups('myconfig.txt')

try:
    print(f'{my_config_file}')
    print(f'{my_config_file:short}')
    print(f'{my_config_file:long}')
    print(f'{my_config_file:foo}')
except TypeError as e:
    print(e)

Output:

Filename myconfig.txt: {}
Filename myconfig.txt: {}
myconfig.txt
Choose between short or long.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM