gpt4 book ai didi

python如何执行调用函数的对象方法,该函数调用同一对象的另一个方法

转载 作者:行者123 更新时间:2023-11-30 22:13:44 25 4
gpt4 key购买 nike

有一个名为start_party的函数,它不属于任何类,是一个打印音乐的独立函数,告诉聚会参与者做一些有趣的事情,例如跳舞或唱歌。

一个可以像聚会参与者一样适应,它有一种感觉,有两种状态:连接和脱离连接。可以根据外部函数告诉一个人执行一个 Action (方法);因此,当人执行该操作时,它首先感受到内部的连接,并使用要求实现的任何方法参与外部功能。外部函数停止(开始聚会结束...),因此该人感觉与这个令人难以置信的时刻脱节,因为它通过打印让我们知道。

所有这些经验的实现如下:

class Feeling():
def __init__(self):
self.data_in = 'into connection'
self.data_out = 'out of connection'


class Person():
def __init__(self):
self.feeling = Feeling()

def execute(self, outer_function, inner_function):
print(self.feeling.data_in)
outer_function(self, inner_function)
print(self.feeling.data_out)

def dance(self):
print(' └[∵┌]└[ ∵ ]┘[┐∵]┘ ')

def sing(self):
print('( ◜◒◝ )')


def start_party(party_participant, inner_function):
print('♬♩♪♩')
party_participant.inner_function()
print('♬♩♪♩')


liz = Person()
liz.execute(start_party, dance)

我尽了最大的努力,但没有编译,它给了我一个:

NameError: name 'dance' is not defined

但主要问题仍然不是编译,而是设计。 (虽然我也需要修复编译。)

期望的输出应该是:

into connection
♬♩♪♩
└[∵┌]└[ ∵ ]┘[┐∵]┘
♬♩♪♩
out of connection

最佳答案

使用getattr()让类方法执行如下:

代码:

def start_party(party_participant, inner_function):
print('♬♩♪♩')
getattr(party_participant, inner_function)()
print('♬♩♪♩')

测试代码:

class Feeling():
def __init__(self):
self.data_in = 'into connection'
self.data_out = 'out of connection'


class Person():
def __init__(self):
self.feeling = Feeling()

def execute(self, outer_function, inner_function):
print(self.feeling.data_in)
outer_function(self, inner_function)
print(self.feeling.data_out)

def dance(self):
print(' └[∵┌]└[ ∵ ]┘[┐∵]┘ ')

def sing(self):
print('( ◜◒◝ )')


def start_party(party_participant, inner_function):
print('♬♩♪♩')
getattr(party_participant, inner_function)()
print('♬♩♪♩')


liz = Person()
liz.execute(start_party, 'dance')

结果:

into connection
♬♩♪♩
└[∵┌]└[ ∵ ]┘[┐∵]┘
♬♩♪♩
out of connection

关于python如何执行调用函数的对象方法,该函数调用同一对象的另一个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50691941/

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