繁体   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