简体   繁体   English

如何访问调用者库中的变量?

[英]How to access variables in the caller library?

Let's say Library A depends on Library B, but in Library B, some piece of codes needs to access an object in Library A. Specifically, I want to check:假设库 A 依赖于库 B,但是在库 B 中,某些代码需要访问库 A 中的对象。具体来说,我想检查:

if isinstance(section, Section)

Because "Section" is a class defined in Library A, how can I make 'Section' available in Library, so that I can import:因为“Section”是在库 A 中定义的一个类,我怎样才能使库中的“Section”可用,以便我可以导入:

from xxx import Section

Is this possible at all?这可能吗? And what's the normal solution?什么是正常的解决方案?

A library is supposed to be a self-contained (other than the libraries it depends on) set of code.一个库应该是一个自包含的(除了它所依赖的库)代码集。 If you have two sets of code that both depend on each other, then they aren't really separate libraries;如果您有两组相互依赖的代码,那么它们并不是真正独立的库; you should put them in the same library.你应该把它们放在同一个库中。 If you want to keep some separation between them, you can encapsulate both as separate objects that reference each other.如果你想在它们之间保持一些分离,你可以将它们封装为相互引用的单独对象。

The usual solution is to pass all the information in Library A to the function or class or such in Library B that needs that information as parameters .通常的解决方案是将库 A 中的所有信息传递给需要该信息作为参数的库 B 中的函数或类等。 These can be parameters in a function call or attributes in an object that is a parameter in a function call or attributes in an object that Library B passes to Library A or something like that.这些可以是函数调用中的参数或对象中的属性,即函数调用中的参数或库 B 传递给库 A 的对象中的属性或类似的东西。

That means programming the functions and classes in Library B so that they ask for all needed information.这意味着对库 B 中的函数和类进行编程,以便它们询问所有需要的信息。 If you don't know what information they need while coding Library B, you are doing it wrong.如果您在编写库 B 时不知道他们需要什么信息,那么您就做错了。

Doing anything else is bad programming practice.做任何其他事情都是糟糕的编程习惯。 You want to make it perfectly clear what information each function and module needs to do its work.您希望完全清楚每个功能和模块需要哪些信息才能完成其工作。 Do that by passing parameters.通过传递参数来做到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM