简体   繁体   English

在python类之间传递参数

[英]Passing a parameter between python classes

I'm attempting to write my first python module. 我正在尝试编写我的第一个python模块。 The module is a wrapper for an api. 该模块是api的包装器。

I'd like to allow users to set an api key in one of two ways: using a static configuration file or dynamically when they initiate the class. 我想允许用户以以下两种方式之一设置api密钥:使用静态配置文件或在启动类时动态使用。

How do I pass the key from __init__.py to functions.py if the key is in fact set dynamically? 如果密钥实际上是动态设置的,如何将密钥从__init__.py传递给functions.py

File structure: 文件结构:

package/
   __init__.py
   config.py
   functions.py

File contents: 文件内容:

__init__.py __init__.py

import config 

class MyClass(object):
    def __init__(self, key):
        self.key = key if key else config.key
        ...

functions.py functions.py

import config 

class MyFunctions(object):
    def __init__(self):
        self.key = ?
        self.base_url = config.base

    def function1(self, my_id):
        endpoint = urlencode({'id':my_id, 'key':self.key})
        ...

config.py config.py

key = 'xxxxxxxxxxx'
base= 'http://xxxxx.com/api'

Assuming you want to set the same key for all the classes in the functions module, do so in the initialization of the package, overwriting the variables set by default in the config module. 假设要为functions模块中的所有类设置相同的键,请在包的初始化中进行设置,并覆盖默认情况下在config模块中设置的变量。

Then import the config module and use the variables 然后导入config模块并使用变量

config.py config.py

key = 1
base_url = 'www.xyz.com/'

__init__.py __init__.py

import config
import functions

class MyClass(object):
    def __init__(self, key=config.key):
        config.key = key

functions.py functions.py

import config 

class MyFunctionsA(object):
    def function1(self, my_id):
        print(config.base_url)
        print(config.key)

class MyFunctionsB(object):
    def function1(self, my_id):
        print(config.base_url)
        print(config.key)

class MyFunctionsC(object):
    def function1(self, my_id):
        print(config.base_url)
        print(config.key)

So you can use them as 因此您可以将它们用作

>>> import package as pk
>>> pk.MyClass(9)
<package.MyClass object at 0x7f2133e96d10>
>>> f1 = pk.functions.MyFunctionsA()
>>> f2 = pk.functions.MyFunctionsB()
>>> f3 = pk.functions.MyFunctionsC()
>>> f1.function1(100)
www.xyz.com/
9
>>> f2.function1(100)
www.xyz.com/
9
>>> f3.function1(100)
www.xyz.com/
9

However, in case the key is an instance attribute of MyFunctions , let the users pass the key to its __init__ , as usual. 但是,如果键是MyFunctions的实例属性,则让用户照常将键传递给它的__init__

Note: I ignore why you need to instantiate MyClass to set things up. 注意:我忽略了为什么您需要实例化MyClass来进行设置。 It may be simpler to use a plain function instead. 改用普通函数可能更简单。

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

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