簡體   English   中英

Python 如何從子模塊訪問父模塊和功能

[英]Python how to access parent's modules and functions from child module

我有三個文件,它們都包含具有相同名稱但定義略有不同的類。 這些類中的某些方法在所有三個文件中都是相同的,因此我將它們抽象到另一個文件utils.py中,它們在原始 class 的“模板”版本中定義。 問題是這些方法調用了原始文件中存在的函數和模塊,而不是這個新文件。

My original approach was to use multiple class inheritance, which would initialize the template class within the scope of the parent class, allowing access to all the functions and modules it requires. 但是,我被指示避免使用多個 class inheritance 並簡單地導入 utils 文件。

導入不會應用與上面提到的 inheritance 相同的范圍邏輯。 所以這里出現了我的問題。 我創建了一個小例子來說明我的意思。 我正在使用一個名為datajoint的模塊。 除了schema基本上是數據庫中的表或表集合之外,您不需要了解太多。

架構.py

import datajoint as dj
from datetime import datetime
import utils

dj.conn()
schema = dj.Schema('adib_example1')
schema.drop()
schema = dj.Schema('adib_example1')

def test_print():
    print("test")

@schema
class Subject(dj.Lookup):
    definition = """
    subject_id: int
    """
    contents = [dict(subject_id=1)] 
    
@schema
class Session(dj.Computed):
    definition = """
    -> Subject
    time: varchar(30)
    """
    
    def make(self, key):
        utils.SessionTemplate.make(self,key)
        
Session.populate() # invokes Session's make(), passing Subject's primary key

方法一

導入范圍不能像 inheritance

實用程序.py

class SessionTemplate():
    
    @staticmethod
    def make(table, key):
        test_print() # parent function usage example
        table.time = f"{datetime.now()}" # parent module usage example
        new_entry = dict(**key, time=table.time)
        table.insert1(new_entry)

錯誤

Traceback (most recent call last):
  File "/home/.anaconda/imported_make/schemas.py", line 30, in <module>
    Session.populate() # invokes Session's make(), passing Subject's primary key
  File "/opt/conda/lib/python3.9/site-packages/datajoint/autopopulate.py", line 153, in populate
    make(dict(key))
  File "/home/.anaconda/imported_make/schemas.py", line 28, in make
    utils.SessionTemplate.make(self,key)
  File "/home/.anaconda/imported_make/utils.py", line 5, in make
    test_print() # parent function usage example
NameError: name 'test_print' is not defined

方法二

將 schemas.py 導入 utils.py會導致循環依賴並需要包含schemas. 在每個導入的 function 和模塊之前,這在我的情況下是不實用的

實用程序.py

import schemas

class SessionTemplate():
    
    @staticmethod
    def make(table, key):
        schemas.test_print() # parent function usage example
        table.time = f"{schemas.datetime.now()}" # parent module usage example
        new_entry = dict(**key, time=table.time)
        table.insert1(new_entry)

錯誤

Traceback (most recent call last):
  File "/home/.anaconda/imported_make/schemas.py", line 3, in <module>
    import utils
  File "/home/.anaconda/imported_make/utils.py", line 1, in <module>
    from schemas import *
  File "/home/.anaconda/imported_make/schemas.py", line 30, in <module>
    Session.populate() # invokes Session's make(), passing Subject's primary key
  File "/opt/conda/lib/python3.9/site-packages/datajoint/autopopulate.py", line 153, in populate
    make(dict(key))
  File "/home/.anaconda/imported_make/schemas.py", line 28, in make
    utils.SessionTemplate.make(self,key)
AttributeError: partially initialized module 'utils' has no attribute 'SessionTemplate' (most likely due to a circular import)

方法 3

使用*導入以避免必須添加schemas. 在每個父函數/模塊之前

from schemas import *

class SessionTemplate():
    
    @staticmethod
    def make(table, key):
        test_print() # parent function usage example
        table.time = f"{datetime.now()}" # parent module usage example
        new_entry = dict(**key, time=table.time)
        table.insert1(new_entry)

錯誤

  • 和以前一樣

我試圖在 python 中完成的事情是不可能的嗎?

老板.py

class tasks():
   def job1(input):
      // do something
      return output
   def job2(input):
      // do something
      return output

工人.py

import boss.tasks
from boss.tasks import job1, job2

input_value = "xyz"

output1 = boss.tasks().job1(input_value)
output2 = boss.tasks().job2(input_value)

暫無
暫無

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

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