首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python如何从子模块访问父模块和函数

Python如何从子模块访问父模块和函数
EN

Stack Overflow用户
提问于 2022-01-28 01:46:28
回答 1查看 492关注 0票数 3

我有三个文件,它们都包含具有相同名称但定义略有不同的类。这些类中的一些方法在所有三个文件中都是相同的,因此我将它们抽象到另一个文件utils.py中,在原始类的“模板”版本中定义它们。问题是这些方法调用原始文件中存在的函数和模块,而不是这个新的。

我最初的方法是使用多类继承,这将在父类的范围内初始化模板类,允许访问它所需的所有函数和模块。但是,指示我避免多个类继承,只需导入utils文件。

导入不应用与上面提到的继承相同的作用域逻辑。所以我的问题就出现了。我创造了一个小例子来说明我的意思。我正在使用一个名为datajoint的模块。除了schema基本上是数据库中的表或表集合之外,您不需要对它了解太多。

schemas.py

代码语言:javascript
复制
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

方法1

导入作用域不像继承那样工作

utils.py

代码语言:javascript
复制
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)

错误

代码语言:javascript
复制
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

方法2

将schemas.py导入utils.py可以工作,但是在每个导入的函数和模块之前都需要包括schemas.,这在我的例子中是不实际的。

utils.py

代码语言:javascript
复制
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)

方法3

*为了避免在每个父函数/模块之前添加schemas.,不知何故不提供对父模块和函数的访问。

代码语言:javascript
复制
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)

错误

代码语言:javascript
复制
Traceback (most recent call last):
  File "/home/.anaconda/imported_make/run.py", line 1, in <module>
    import schemas
  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 7, in make
    test_print() # parent function usage example
NameError: name 'test_print' is not defined

我知道import *是一种糟糕的实践,但是在这种情况下,如果它有效的话,它会很好,而且我也不知道为什么它不能。

EN

回答 1

Stack Overflow用户

发布于 2022-01-28 04:22:50

boss.py

代码语言:javascript
复制
class tasks():
   def job1(input):
      // do something
      return output
   def job2(input):
      // do something
      return output

worker.py

代码语言:javascript
复制
import boss.tasks
from boss.tasks import job1, job2

input_value = "xyz"

output1 = boss.tasks().job1(input_value)
output2 = boss.tasks().job2(input_value)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70887945

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档