簡體   English   中英

使用 Python 中的外部/幫助文件(即模塊)修改 class 屬性(自身)的最佳方法是什么?

[英]What is the best way to modify a class attribute (self) using an external/helper file (i.e. module) in Python?

我有一個Flask應用程序變得非常大,我想將一些 class 函數移動到外部文件,因為文件超過 500 行。 這些函數有一些邏輯來修改一些 class 屬性並且很大(就行而言)。

下面是一個演示場景,我試圖跟蹤數字請求。 讓我們假設increment是一個巨大的 function 並且我想將一些功能移動到幫助器 function 即help_to_add ,這需要修改一些 ZA2F2ED4F8EBC2CBB4C21A29DC40AB6 屬性。

app.py

from flask import make_response
from modules import help_to_add
import sys

sys.path.append('..')
from untitled import app


class Main:
    def __init__(self):
        self.requests = 0

    def increment(self):
        self = help_to_add(self)


main = Main()


@app.route('/', methods=['POST'])
def hello():
    v1 = add(3, 5)
    main.increment()
    v2 = add(4, 6)
    main.increment()

    return make_response('{}, {}\n'.format(v1, v2), 200)


if __name__ == '__main__':
    app.run(port='7000', host='0.0.0.0')

modules.py

def help_to_add(object):
    object.requests += 1
    return object

_ init _.py

from flask import Flask

app = Flask(__name__)

現在我通過將self作為參數傳遞來實現這一點,但它對我來說看起來不是很干凈。 我想知道是否有更好的方法來做到這一點。 I know that ideally we should have this function ( help_to_add ) in the same file under the class and I should try to move the static methods to a helper function and reorganize my code. 我已經完成了所有這些,但我只有很多功能需要讀取/修改 class 屬性,我必須將其中一些移動到單獨的模塊中。

PS:最初,我使用的是global變量,這個文件(即modules.py )充當了一個包含所有輔助函數的文件。 我正在嘗試將整個代碼庫轉移到使用類並完全避免global變量。

就個人而言,如果您真的想將一個 class 的代碼拆分為多個文件(我自己不會這樣做),我認為以下模式沒有任何問題:

# In one file
from my_implementation import my_implementation

class Foo:
    def big_function_bar(self):
        my_implementation(self)

# In another file
def my_implementation(self):
    pass    # do stuff you need to do

這將按預期工作。 這可能會使事情變得有點混亂,因為您將在文件中跳轉,試圖找出哪些代碼將引導到哪里。

關於這一點,您無需執行以下操作:

self = help_to_add(self)

相反,您可以簡單地執行以下操作:

help_to_add(self)

這是因為對象在 Python 中通過引用傳遞,因此您對object所做的任何更改都將針對該實例,而不是它的副本。

暫無
暫無

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

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