how to import only the class methods in python

后端 未结 5 1994
梦谈多话
梦谈多话 2020-12-19 04:50

I have a GP.py file that I am then running a MyBot.py file from.

In the MyBot.py file, I have the line

from GP import *

I have a su

相关标签:
5条回答
  • 2020-12-19 05:30

    You cannot import class methods separately, you have to import the classes. You can do this by enumerating the classes you want to import:

    from GP import class1, class2, class3
    

    Note that this will still load the entire module. This always happens if you import anything from the module. If you have code in that module that you do not want to be executed when the module is imported, you can protect it like this:

    if __name__ == "__main__":
        # put code here
    

    Code inside the block will only be executed if the module is run directly, not if it is imported.

    0 讨论(0)
  • 2020-12-19 05:32

    _single_leading_underscore: weak "internal use" indicator. E.g. from M import * does not import objects whose name starts with an underscore.

    Use this instead:

    from GP import SomeClass
    

    Have a look at PEP-8 (Python Guidelines) if you want to use import *

    Modules that are designed for use via from M import * should use the __all__ mechanism to prevent exporting globals

    0 讨论(0)
  • 2020-12-19 05:55

    It is not recommended to import all from a module. Zen of Python says "Explicit is better than Implicit"

    It may have some side effects by overriding an existing name. You should always keep control on the namespace.

    You can import your classes and function this way:

    from GP import MyClass, my_function
    

    An alternative is to import the module itself

    import GP
    GP.my_function()
    GP.MyClass()
    

    This way, you create a namespace for the GP module and avoid to overwrite something.

    I hope it helps

    0 讨论(0)
  • 2020-12-19 05:55

    import * indeed import all classes, functions,variables and etc..

    if you want to import only specific class use

    from GP import class_name
    

    and as far as i know you cannot import only class methods

    0 讨论(0)
  • 2020-12-19 05:56

    If you want to import just some methods from class

    from GP.MyClass import MyFunction
    
    0 讨论(0)
提交回复
热议问题