为什么说python类可以“更好”地实现为字典和一些函数?

2024-09-29 01:27:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我在对问题Python progression path - From apprentice to guru的回答中看到了这个说明。在

9. Annoy your cubicle mates every time they present you with a Python class. Claim it could be "better" implemented as a dictionary plus some functions. Embrace functional programming.

但我不明白。这和函数式编程有什么关系?在


Tags: topathfromyouyourtimetheyevery
2条回答

之所以出现在“Python progression path”中,是因为它反映了这样一种认识:Python类只是函数和dict的语法糖,通过直接使用函数和dict,人们需要的语言元素更少,从而使程序更“纯粹”

当然,这完全是误入歧途,这就是为什么它很有趣。或者我只是还没有达到开悟的境界?在

这意味着:

class A:
    def __init__(this):
        this.count = 0
    def bump(this):
        this.count += 1

a = A()
a.bump()

可由以下内容代替:

^{pr2}$

或者,更实用的风格,通过返回副本来避免副作用:

def bumpedA(anA):
    newA = {'count': (anA['count'] + 1 )}
    return newA

a = constructA()
a = bumpedA(a)

这是基本的模式——您可以通过将方法放入字典本身(javascript样式)来获得多态性,并且通常使用dict和函数来重构整个Python对象系统。在

相关问题 更多 >