将State传递给函数而不是在类实例上调用方法(Passing State into functions versus calling methods on class instances)

编程入门 行业动态 更新时间:2024-10-28 15:31:11
将State传递给函数而不是在类实例上调用方法(Passing State into functions versus calling methods on class instances)

我已经开始研究一些有点遗留的代码库,将其更新为Python 3.构建此代码的设计人员/工程师决定将它们组合成一个主要业务逻辑的设置,而不是完整的OOP或全功能。在作为数据结构和类实例的单个对象上执行:

class StateHolder: def __init__(self, a, b, c): self.a = a self.b = b self.c = c def method_one(self, x, y): self.a = a + x self.b = b + y def modify_c(state_holder, new_c): state_holder.c += new_c def main(): example = StateHolder(1, 2, 3) example.method_one(4, 5) modify_c(example, 6)

像modify_c这样的函数的数量远远超过了类中的方法,所以它并不像我在这里看到的那么简单。 具体来说,一次只有一个StateHolder实例,并且所有方法都直接对它进行操作,而不是创建新副本并将其传回。

我的问题是:如果我有无限的时间来重构这个,我应该遵循构建和保存数据的系统吗? 我应该将所有函数(如modify_c到StateHolder ,还是应该将所有StateHolder方法移出并传递状态?

I've begun work on a somewhat legacy codebase, updating it to Python 3. The designer/engineer who built this decided that instead of going full OOP or full functional, they'd combine them into a set-up where the main business logic is performed on a single object that acts as both data structure and class instance:

class StateHolder: def __init__(self, a, b, c): self.a = a self.b = b self.c = c def method_one(self, x, y): self.a = a + x self.b = b + y def modify_c(state_holder, new_c): state_holder.c += new_c def main(): example = StateHolder(1, 2, 3) example.method_one(4, 5) modify_c(example, 6)

The number of functions like modify_c far outnumber the methods within the class, so it's not nearly as simple as I've made it look here. To be specific, there is only ever one instance of StateHolder at a time, and all of the methods operate on it directly, instead of creating a new copy and passing it back.

My question is: if I were given unlimited time to refactor this, which system for structuring and holding the data should I follow? Should I move all of the functions like modify_c into StateHolder, or should I move all of the StateHolder methods out and pass state around?

更多推荐

本文发布于:2023-08-05 14:38:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1434122.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:是在   而不   函数   实例   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!