gpt4 book ai didi

python - 如何判断最后一个函数是否在类: Python中被调用

转载 作者:太空宇宙 更新时间:2023-11-03 15:49:51 25 4
gpt4 key购买 nike

我有一个类似于以下内容的 Python 类:

class BuildSentence(object):

def __init__(self, intro):
self.sentence = intro

def name(self, na):
self.sentence += "; my name is %s" % (na)

def surname(self, su):
self.sentence += "; my surname is %s" % (su)

def age(self, ag):
self.sentence += "; I am %d years old" % (ag)

def final_sentence(self):
self.sentence += "."
return do_something_with(self.sentence)

我希望在所有必需的函数完成时自动调用final_sentence'函数。 'final_sentence' 函数不一定返回字符串,它可能是整数或列表。我不确定是否可以识别最后调用的函数?

例如:

s = BuildSentence("Hello")
answer = s.name("Foo").age(40)

应该“do_something_with”:

Hello; my is Foo; I am 40 years old.

最佳答案

您可以使用__str__方法,每当需要字符串时就会自动调用该方法。

class BuildSentence(object):
def __init__(self, intro):
self.sentence = intro
self.templates = {
'name': "; my name is %s",
'surname': "; my surname is %s",
'age': "; I am %d years old",
}

def __getattr__(self, attr):
def set(value):
self.sentence += self.templates.pop(attr) % value
return self
return set

def __str__(self):
return self.sentence + '.'

示例:

>>> print(BuildSentence('Hello').name('Tim').age(45))
Hello; my name is Tim; I am 45 years old.

关于python - 如何判断最后一个函数是否在类: Python中被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41414622/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com