Hướng dẫn python import class by string - lớp nhập python theo chuỗi

Thêm một chút tinh tế vào các câu trả lời hiện có ....

Tùy thuộc vào trường hợp sử dụng, có thể hơi bất tiện khi phải chỉ định rõ ràng đường dẫn đầy đủ (ví dụ:

from modes.modes import Mode

class Foo(Mode):
    def __init__(self, *arg, **kwargs):
        super(Foo, self).__init__(*arg, **kwargs)
        
    def run(self):
        self.LOG.info(f"This is FOO!")
1) của lớp/phương thức bạn muốn nhập. Trên đỉnh của nhập khẩu, chúng ta có thể tận dụng
from modes.modes import Mode

class Foo(Mode):
    def __init__(self, *arg, **kwargs):
        super(Foo, self).__init__(*arg, **kwargs)
        
    def run(self):
        self.LOG.info(f"This is FOO!")
2 để làm cho mọi thứ trở nên sạch sẽ hơn.

Giả sử tôi có gói Python, như vậy:

├── modes
│   ├── __init__.py
│   ├── bar.py
│   ├── foo.py
│   ├── modes.py

from modes.modes import Mode

class Foo(Mode):
    def __init__(self, *arg, **kwargs):
        super(Foo, self).__init__(*arg, **kwargs)
        
    def run(self):
        self.LOG.info(f"This is FOO!")
3, giả sử, có một số lớp/chức năng mà chúng tôi muốn sử dụng ở một nơi khác trong chương trình của chúng tôi:

from modes.modes import Mode

class Foo(Mode):
    def __init__(self, *arg, **kwargs):
        super(Foo, self).__init__(*arg, **kwargs)
        
    def run(self):
        self.LOG.info(f"This is FOO!")

Với đối số dòng lệnh, tôi có thể chuyển một đối số tương ứng với chế độ mà tôi muốn chạy. Tôi muốn có thể như vậy như thế này:

def set_mode(mode):
    """  """
    import importlib
    module = importlib.import_module('modes.foo')
    getattr(module, mode)().run()

đầu ra nào:

>> set_mode("Foo")
>> engine_logger:INFO - This is FOO!

Điều đó hoạt động tốt, tuy nhiên những gì chúng tôi thực sự muốn nhận được là:

def set_mode(mode):
    """  """
    import importlib
    module = importlib.import_module('modes')  # only import the package, not modules explicitely
    getattr(module, mode)().run()

Điều này gây ra lỗi:

>> set_mode("Foo")
>> AttributeError: module 'modes' has no attribute 'Foo'

Tuy nhiên, chúng ta có thể thêm phần sau vào

from modes.modes import Mode

class Foo(Mode):
    def __init__(self, *arg, **kwargs):
        super(Foo, self).__init__(*arg, **kwargs)
        
    def run(self):
        self.LOG.info(f"This is FOO!")
4:

from .foo import Foo
from .bar import Bar

Sau đó, chúng ta có thể làm:

>> set_mode("Foo")
>> engine_logger:INFO - This is FOO!

>> set_mode("Bar")
>> engine_logger:INFO - This is BAR!

Trong các thế giới khác, tất cả các mô -đun/chức năng/lớp phụ chúng tôi nhập trong init.py sẽ được tìm thấy trực tiếp với ImportLib.Import_Module (...), mà không phải chỉ định đường dẫn đầy đủ từ bên ngoài.

Xem thảo luận

Cải thiện bài viết

Lưu bài viết

  • Đọc
  • Bàn luận
  • Xem thảo luận

    Cải thiện bài viết

    Lưu bài viết

    Đọc

    Bàn luận For more information, refer to Python Modules

    Python cung cấp một tính năng để tạo và lưu trữ các lớp và phương pháp và lưu trữ chúng để sử dụng tiếp. Tệp chứa các bộ phương thức và lớp này được gọi là mô -đun. Một mô -đun có thể có các mô -đun khác bên trong nó. A simple example of importing a module is shown below in which, there are 2 files that are module.py and importing_mod.py in the same directory. The module.py file acts as a module to import_mod.py file.

    module.py

    from modes.modes import Mode
    
    class Foo(Mode):
        def __init__(self, *arg, **kwargs):
            super(Foo, self).__init__(*arg, **kwargs)
            
        def run(self):
            self.LOG.info(f"This is FOO!")
    
    5
    from modes.modes import Mode
    
    class Foo(Mode):
        def __init__(self, *arg, **kwargs):
            super(Foo, self).__init__(*arg, **kwargs)
            
        def run(self):
            self.LOG.info(f"This is FOO!")
    
    6
    from modes.modes import Mode
    
    class Foo(Mode):
        def __init__(self, *arg, **kwargs):
            super(Foo, self).__init__(*arg, **kwargs)
            
        def run(self):
            self.LOG.info(f"This is FOO!")
    
    7
    from modes.modes import Mode
    
    class Foo(Mode):
        def __init__(self, *arg, **kwargs):
            super(Foo, self).__init__(*arg, **kwargs)
            
        def run(self):
            self.LOG.info(f"This is FOO!")
    
    8

    from modes.modes import Mode
    
    class Foo(Mode):
        def __init__(self, *arg, **kwargs):
            super(Foo, self).__init__(*arg, **kwargs)
            
        def run(self):
            self.LOG.info(f"This is FOO!")
    
    9
    def set_mode(mode):
        """  """
        import importlib
        module = importlib.import_module('modes.foo')
        getattr(module, mode)().run()
    
    0
    def set_mode(mode):
        """  """
        import importlib
        module = importlib.import_module('modes.foo')
        getattr(module, mode)().run()
    
    1
    def set_mode(mode):
        """  """
        import importlib
        module = importlib.import_module('modes.foo')
        getattr(module, mode)().run()
    
    2
    def set_mode(mode):
        """  """
        import importlib
        module = importlib.import_module('modes.foo')
        getattr(module, mode)().run()
    
    3
    from modes.modes import Mode
    
    class Foo(Mode):
        def __init__(self, *arg, **kwargs):
            super(Foo, self).__init__(*arg, **kwargs)
            
        def run(self):
            self.LOG.info(f"This is FOO!")
    
    7
    def set_mode(mode):
        """  """
        import importlib
        module = importlib.import_module('modes.foo')
        getattr(module, mode)().run()
    
    5

    Tệp nhập khẩu_mod.py

    def set_mode(mode):
        """  """
        import importlib
        module = importlib.import_module('modes.foo')
        getattr(module, mode)().run()
    
    6
    def set_mode(mode):
        """  """
        import importlib
        module = importlib.import_module('modes.foo')
        getattr(module, mode)().run()
    
    7

    def set_mode(mode):
        """  """
        import importlib
        module = importlib.import_module('modes.foo')
        getattr(module, mode)().run()
    
    8
    def set_mode(mode):
        """  """
        import importlib
        module = importlib.import_module('modes.foo')
        getattr(module, mode)().run()
    
    9
    >> set_mode("Foo")
    >> engine_logger:INFO - This is FOO!
    
    0

    Đầu ra

    Hi! User_1 Welcome to GfG

    Đây tải các mô -đun hoặc lớp

    Các mô -đun được thêm vào trong mã trên là nhập các mô -đun tĩnh, tức là trong thời gian biên dịch. Trong Python, chúng ta có thể nhập các mô -đun một cách linh hoạt bằng hai cách

    • Bằng cách sử dụng phương thức __Import __ ():
      >> set_mode("Foo")
      >> engine_logger:INFO - This is FOO!
      
      1 là một phương thức khó khăn (các phương thức bắt đầu lớp và kết thúc với dấu gạch dưới kép cũng được gọi là phương thức ma thuật) và tất cả các lớp sở hữu nó. Nó được sử dụng để nhập một mô -đun hoặc một lớp trong trường hợp của một lớp. Có một ví dụ về phương pháp này được đưa ra như sau, trong đó chúng tôi sẽ nhập một mô -đun một cách linh hoạt. Tệp mô -đun hiện được sửa đổi là:
      >> set_mode("Foo")
      >> engine_logger:INFO - This is FOO!
      
      1 is a dunder method (methods of class starting and ending with double underscore also called magic method) and all classes own it. It is used to import a module or a class within the instance of a class. There is an example on this method given as follows, in which we will be importing a module dynamically. The module file is now modified as:

      module.py

      >> set_mode("Foo")
      >> engine_logger:INFO - This is FOO!
      
      2
      >> set_mode("Foo")
      >> engine_logger:INFO - This is FOO!
      
      3

      from modes.modes import Mode
      
      class Foo(Mode):
          def __init__(self, *arg, **kwargs):
              super(Foo, self).__init__(*arg, **kwargs)
              
          def run(self):
              self.LOG.info(f"This is FOO!")
      
      9
      from modes.modes import Mode
      
      class Foo(Mode):
          def __init__(self, *arg, **kwargs):
              super(Foo, self).__init__(*arg, **kwargs)
              
          def run(self):
              self.LOG.info(f"This is FOO!")
      
      5
      from modes.modes import Mode
      
      class Foo(Mode):
          def __init__(self, *arg, **kwargs):
              super(Foo, self).__init__(*arg, **kwargs)
              
          def run(self):
              self.LOG.info(f"This is FOO!")
      
      6
      from modes.modes import Mode
      
      class Foo(Mode):
          def __init__(self, *arg, **kwargs):
              super(Foo, self).__init__(*arg, **kwargs)
              
          def run(self):
              self.LOG.info(f"This is FOO!")
      
      7
      from modes.modes import Mode
      
      class Foo(Mode):
          def __init__(self, *arg, **kwargs):
              super(Foo, self).__init__(*arg, **kwargs)
              
          def run(self):
              self.LOG.info(f"This is FOO!")
      
      8

      >> set_mode("Foo")
      >> engine_logger:INFO - This is FOO!
      
      9
      def set_mode(mode):
          """  """
          import importlib
          module = importlib.import_module('modes.foo')
          getattr(module, mode)().run()
      
      0
      def set_mode(mode):
          """  """
          import importlib
          module = importlib.import_module('modes.foo')
          getattr(module, mode)().run()
      
      1
      def set_mode(mode):
          """  """
          import importlib
          module = importlib.import_module('modes.foo')
          getattr(module, mode)().run()
      
      2
      def set_mode(mode):
          """  """
          import importlib
          module = importlib.import_module('modes.foo')
          getattr(module, mode)().run()
      
      3
      from modes.modes import Mode
      
      class Foo(Mode):
          def __init__(self, *arg, **kwargs):
              super(Foo, self).__init__(*arg, **kwargs)
              
          def run(self):
              self.LOG.info(f"This is FOO!")
      
      7
      def set_mode(mode):
          """  """
          import importlib
          module = importlib.import_module('modes.foo')
          getattr(module, mode)().run()
      
      5

      Dynamic_import.py

      >> set_mode("Foo")
      >> engine_logger:INFO - This is FOO!
      
      2
      def set_mode(mode):
          """  """
          import importlib
          module = importlib.import_module('modes')  # only import the package, not modules explicitely
          getattr(module, mode)().run()
      
      7

      from modes.modes import Mode
      
      class Foo(Mode):
          def __init__(self, *arg, **kwargs):
              super(Foo, self).__init__(*arg, **kwargs)
              
          def run(self):
              self.LOG.info(f"This is FOO!")
      
      9
      from modes.modes import Mode
      
      class Foo(Mode):
          def __init__(self, *arg, **kwargs):
              super(Foo, self).__init__(*arg, **kwargs)
              
          def run(self):
              self.LOG.info(f"This is FOO!")
      
      5
      >> set_mode("Foo")
      >> AttributeError: module 'modes' has no attribute 'Foo'
      
      0
      >> set_mode("Foo")
      >> AttributeError: module 'modes' has no attribute 'Foo'
      
      1
      >> set_mode("Foo")
      >> AttributeError: module 'modes' has no attribute 'Foo'
      
      2

      >> set_mode("Foo")
      >> engine_logger:INFO - This is FOO!
      
      9
      >> set_mode("Foo")
      >> AttributeError: module 'modes' has no attribute 'Foo'
      
      4
      >> set_mode("Foo")
      >> AttributeError: module 'modes' has no attribute 'Foo'
      
      5
      >> set_mode("Foo")
      >> AttributeError: module 'modes' has no attribute 'Foo'
      
      6
      >> set_mode("Foo")
      >> AttributeError: module 'modes' has no attribute 'Foo'
      
      7

      >> set_mode("Foo")
      >> engine_logger:INFO - This is FOO!
      
      9
      >> set_mode("Foo")
      >> AttributeError: module 'modes' has no attribute 'Foo'
      
      9
      >> set_mode("Foo")
      >> AttributeError: module 'modes' has no attribute 'Foo'
      
      5
      from .foo import Foo
      from .bar import Bar
      
      1
      from .foo import Foo
      from .bar import Bar
      
      2

      >> set_mode("Foo")
      >> engine_logger:INFO - This is FOO!
      
      9
      from .foo import Foo
      from .bar import Bar
      
      4
      from .foo import Foo
      from .bar import Bar
      
      5
      def set_mode(mode):
          """  """
          import importlib
          module = importlib.import_module('modes.foo')
          getattr(module, mode)().run()
      
      5

      from .foo import Foo
      from .bar import Bar
      
      7
      >> set_mode("Foo")
      >> AttributeError: module 'modes' has no attribute 'Foo'
      
      5
      from .foo import Foo
      from .bar import Bar
      
      9
      >> set_mode("Foo")
      >> engine_logger:INFO - This is FOO!
      
      >> set_mode("Bar")
      >> engine_logger:INFO - This is BAR!
      
      0
      >> set_mode("Foo")
      >> engine_logger:INFO - This is FOO!
      
      >> set_mode("Bar")
      >> engine_logger:INFO - This is BAR!
      
      1
      >> set_mode("Foo")
      >> engine_logger:INFO - This is FOO!
      
      >> set_mode("Bar")
      >> engine_logger:INFO - This is BAR!
      
      2

      Đầu ra

      Hi! User_1 Welcome to GfG
    • Đây tải các mô -đun hoặc lớp Modules can be imported dynamically by the imp module in python. The example below is a demonstration on the using the imp module. It provides the
      >> set_mode("Foo")
      >> engine_logger:INFO - This is FOO!
      
      >> set_mode("Bar")
      >> engine_logger:INFO - This is BAR!
      
      4 method to find the module and the
      >> set_mode("Foo")
      >> engine_logger:INFO - This is FOO!
      
      >> set_mode("Bar")
      >> engine_logger:INFO - This is BAR!
      
      5 method to import it.

      Dynamic_import.py

      Các mô -đun được thêm vào trong mã trên là nhập các mô -đun tĩnh, tức là trong thời gian biên dịch. Trong Python, chúng ta có thể nhập các mô -đun một cách linh hoạt bằng hai cách

      Bằng cách sử dụng phương thức __Import __ ():

      >> set_mode("Foo")
      >> engine_logger:INFO - This is FOO!
      
      1 là một phương thức khó khăn (các phương thức bắt đầu lớp và kết thúc với dấu gạch dưới kép cũng được gọi là phương thức ma thuật) và tất cả các lớp sở hữu nó. Nó được sử dụng để nhập một mô -đun hoặc một lớp trong trường hợp của một lớp. Có một ví dụ về phương pháp này được đưa ra như sau, trong đó chúng tôi sẽ nhập một mô -đun một cách linh hoạt. Tệp mô -đun hiện được sửa đổi là:

      >> set_mode("Foo")
      >> engine_logger:INFO - This is FOO!
      
      2
      >> set_mode("Foo")
      >> engine_logger:INFO - This is FOO!
      
      3

      from modes.modes import Mode
      
      class Foo(Mode):
          def __init__(self, *arg, **kwargs):
              super(Foo, self).__init__(*arg, **kwargs)
              
          def run(self):
              self.LOG.info(f"This is FOO!")
      
      9
      Hi! User_1 Welcome to GfG
      3
      Hi! User_1 Welcome to GfG
      4

      from modes.modes import Mode
      
      class Foo(Mode):
          def __init__(self, *arg, **kwargs):
              super(Foo, self).__init__(*arg, **kwargs)
              
          def run(self):
              self.LOG.info(f"This is FOO!")
      
      9
      from modes.modes import Mode
      
      class Foo(Mode):
          def __init__(self, *arg, **kwargs):
              super(Foo, self).__init__(*arg, **kwargs)
              
          def run(self):
              self.LOG.info(f"This is FOO!")
      
      5
      from modes.modes import Mode
      
      class Foo(Mode):
          def __init__(self, *arg, **kwargs):
              super(Foo, self).__init__(*arg, **kwargs)
              
          def run(self):
              self.LOG.info(f"This is FOO!")
      
      6
      from modes.modes import Mode
      
      class Foo(Mode):
          def __init__(self, *arg, **kwargs):
              super(Foo, self).__init__(*arg, **kwargs)
              
          def run(self):
              self.LOG.info(f"This is FOO!")
      
      7
      from modes.modes import Mode
      
      class Foo(Mode):
          def __init__(self, *arg, **kwargs):
              super(Foo, self).__init__(*arg, **kwargs)
              
          def run(self):
              self.LOG.info(f"This is FOO!")
      
      8

      >> set_mode("Foo")
      >> engine_logger:INFO - This is FOO!
      
      9
      def set_mode(mode):
          """  """
          import importlib
          module = importlib.import_module('modes.foo')
          getattr(module, mode)().run()
      
      0
      def set_mode(mode):
          """  """
          import importlib
          module = importlib.import_module('modes.foo')
          getattr(module, mode)().run()
      
      1
      def set_mode(mode):
          """  """
          import importlib
          module = importlib.import_module('modes.foo')
          getattr(module, mode)().run()
      
      2
      def set_mode(mode):
          """  """
          import importlib
          module = importlib.import_module('modes.foo')
          getattr(module, mode)().run()
      
      3
      from modes.modes import Mode
      
      class Foo(Mode):
          def __init__(self, *arg, **kwargs):
              super(Foo, self).__init__(*arg, **kwargs)
              
          def run(self):
              self.LOG.info(f"This is FOO!")
      
      7
      def set_mode(mode):
          """  """
          import importlib
          module = importlib.import_module('modes.foo')
          getattr(module, mode)().run()
      
      5

      >> set_mode("Foo")
      >> engine_logger:INFO - This is FOO!
      
      2
      def set_mode(mode):
          """  """
          import importlib
          module = importlib.import_module('modes')  # only import the package, not modules explicitely
          getattr(module, mode)().run()
      
      7

      from modes.modes import Mode
      
      class Foo(Mode):
          def __init__(self, *arg, **kwargs):
              super(Foo, self).__init__(*arg, **kwargs)
              
          def run(self):
              self.LOG.info(f"This is FOO!")
      
      9
      Hi! User_1 Welcome to GfG
      3
      Hi! User_1 Welcome to GfG
      4

      from modes.modes import Mode
      
      class Foo(Mode):
          def __init__(self, *arg, **kwargs):
              super(Foo, self).__init__(*arg, **kwargs)
              
          def run(self):
              self.LOG.info(f"This is FOO!")
      
      9
      from modes.modes import Mode
      
      class Foo(Mode):
          def __init__(self, *arg, **kwargs):
              super(Foo, self).__init__(*arg, **kwargs)
              
          def run(self):
              self.LOG.info(f"This is FOO!")
      
      5
      >> set_mode("Foo")
      >> AttributeError: module 'modes' has no attribute 'Foo'
      
      0
      >> set_mode("Foo")
      >> AttributeError: module 'modes' has no attribute 'Foo'
      
      1
      >> set_mode("Foo")
      >> AttributeError: module 'modes' has no attribute 'Foo'
      
      2

      from modes.modes import Mode
      
      class Foo(Mode):
          def __init__(self, *arg, **kwargs):
              super(Foo, self).__init__(*arg, **kwargs)
              
          def run(self):
              self.LOG.info(f"This is FOO!")
      
      05
      from modes.modes import Mode
      
      class Foo(Mode):
          def __init__(self, *arg, **kwargs):
              super(Foo, self).__init__(*arg, **kwargs)
              
          def run(self):
              self.LOG.info(f"This is FOO!")
      
      06

      >> set_mode("Foo")
      >> engine_logger:INFO - This is FOO!
      
      9
      >> set_mode("Foo")
      >> AttributeError: module 'modes' has no attribute 'Foo'
      
      4
      >> set_mode("Foo")
      >> AttributeError: module 'modes' has no attribute 'Foo'
      
      5
      >> set_mode("Foo")
      >> AttributeError: module 'modes' has no attribute 'Foo'
      
      6
      >> set_mode("Foo")
      >> AttributeError: module 'modes' has no attribute 'Foo'
      
      7

      >> set_mode("Foo")
      >> engine_logger:INFO - This is FOO!
      
      9
      def set_mode(mode):
          """  """
          import importlib
          module = importlib.import_module('modes.foo')
          getattr(module, mode)().run()
      
      0
      from modes.modes import Mode
      
      class Foo(Mode):
          def __init__(self, *arg, **kwargs):
              super(Foo, self).__init__(*arg, **kwargs)
              
          def run(self):
              self.LOG.info(f"This is FOO!")
      
      12

      from modes.modes import Mode
      
      class Foo(Mode):
          def __init__(self, *arg, **kwargs):
              super(Foo, self).__init__(*arg, **kwargs)
              
          def run(self):
              self.LOG.info(f"This is FOO!")
      
      9
      Hi! User_1 Welcome to GfG
      3
      Hi! User_1 Welcome to GfG
      4

      >> set_mode("Foo")
      >> engine_logger:INFO - This is FOO!
      
      9
      >> set_mode("Foo")
      >> AttributeError: module 'modes' has no attribute 'Foo'
      
      9
      >> set_mode("Foo")
      >> AttributeError: module 'modes' has no attribute 'Foo'
      
      5
      from .foo import Foo
      from .bar import Bar
      
      1
      from .foo import Foo
      from .bar import Bar
      
      2

      from modes.modes import Mode
      
      class Foo(Mode):
          def __init__(self, *arg, **kwargs):
              super(Foo, self).__init__(*arg, **kwargs)
              
          def run(self):
              self.LOG.info(f"This is FOO!")
      
      23
      from modes.modes import Mode
      
      class Foo(Mode):
          def __init__(self, *arg, **kwargs):
              super(Foo, self).__init__(*arg, **kwargs)
              
          def run(self):
              self.LOG.info(f"This is FOO!")
      
      24

      from modes.modes import Mode
      
      class Foo(Mode):
          def __init__(self, *arg, **kwargs):
              super(Foo, self).__init__(*arg, **kwargs)
              
          def run(self):
              self.LOG.info(f"This is FOO!")
      
      25
      from modes.modes import Mode
      
      class Foo(Mode):
          def __init__(self, *arg, **kwargs):
              super(Foo, self).__init__(*arg, **kwargs)
              
          def run(self):
              self.LOG.info(f"This is FOO!")
      
      26

      >> set_mode("Foo")
      >> engine_logger:INFO - This is FOO!
      
      9
      >> set_mode("Foo")
      >> AttributeError: module 'modes' has no attribute 'Foo'
      
      4
      >> set_mode("Foo")
      >> AttributeError: module 'modes' has no attribute 'Foo'
      
      5
      >> set_mode("Foo")
      >> AttributeError: module 'modes' has no attribute 'Foo'
      
      6
      >> set_mode("Foo")
      >> AttributeError: module 'modes' has no attribute 'Foo'
      
      7

      >> set_mode("Foo")
      >> engine_logger:INFO - This is FOO!
      
      9
      def set_mode(mode):
          """  """
          import importlib
          module = importlib.import_module('modes.foo')
          getattr(module, mode)().run()
      
      0
      from modes.modes import Mode
      
      class Foo(Mode):
          def __init__(self, *arg, **kwargs):
              super(Foo, self).__init__(*arg, **kwargs)
              
          def run(self):
              self.LOG.info(f"This is FOO!")
      
      12

      >> set_mode("Foo")
      >> engine_logger:INFO - This is FOO!
      
      9
      >> set_mode("Foo")
      >> AttributeError: module 'modes' has no attribute 'Foo'
      
      9
      >> set_mode("Foo")
      >> AttributeError: module 'modes' has no attribute 'Foo'
      
      5
      from .foo import Foo
      from .bar import Bar
      
      1
      from .foo import Foo
      from .bar import Bar
      
      2

      from .foo import Foo
      from .bar import Bar
      
      7
      >> set_mode("Foo")
      >> AttributeError: module 'modes' has no attribute 'Foo'
      
      5
      from .foo import Foo
      from .bar import Bar
      
      9
      >> set_mode("Foo")
      >> engine_logger:INFO - This is FOO!
      
      >> set_mode("Bar")
      >> engine_logger:INFO - This is BAR!
      
      0
      >> set_mode("Foo")
      >> engine_logger:INFO - This is FOO!
      
      >> set_mode("Bar")
      >> engine_logger:INFO - This is BAR!
      
      1
      >> set_mode("Foo")
      >> engine_logger:INFO - This is FOO!
      
      >> set_mode("Bar")
      >> engine_logger:INFO - This is BAR!
      
      2

      Sử dụng mô -đun IMP: Các mô -đun có thể được nhập động bằng mô -đun IMP trong Python. Ví dụ dưới đây là một minh chứng về việc sử dụng mô -đun IMP. Nó cung cấp phương thức

      >> set_mode("Foo")
      >> engine_logger:INFO - This is FOO!
      
      >> set_mode("Bar")
      >> engine_logger:INFO - This is BAR!
      
      4 để tìm mô -đun và phương thức
      >> set_mode("Foo")
      >> engine_logger:INFO - This is FOO!
      
      >> set_mode("Bar")
      >> engine_logger:INFO - This is BAR!
      
      5 để nhập nó.

      from modes.modes import Mode
      
      class Foo(Mode):
          def __init__(self, *arg, **kwargs):
              super(Foo, self).__init__(*arg, **kwargs)
              
          def run(self):
              self.LOG.info(f"This is FOO!")
      
      9
      from modes.modes import Mode
      
      class Foo(Mode):
          def __init__(self, *arg, **kwargs):
              super(Foo, self).__init__(*arg, **kwargs)
              
          def run(self):
              self.LOG.info(f"This is FOO!")
      
      51
      from modes.modes import Mode
      
      class Foo(Mode):
          def __init__(self, *arg, **kwargs):
              super(Foo, self).__init__(*arg, **kwargs)
              
          def run(self):
              self.LOG.info(f"This is FOO!")
      
      52
      >> set_mode("Foo")
      >> engine_logger:INFO - This is FOO!
      
      >> set_mode("Bar")
      >> engine_logger:INFO - This is BAR!
      
      1
      from modes.modes import Mode
      
      class Foo(Mode):
          def __init__(self, *arg, **kwargs):
              super(Foo, self).__init__(*arg, **kwargs)
              
          def run(self):
              self.LOG.info(f"This is FOO!")
      
      54
      def set_mode(mode):
          """  """
          import importlib
          module = importlib.import_module('modes.foo')
          getattr(module, mode)().run()
      
      5

      Đầu ra

      Hi! User_1 Welcome to GfG

    Làm thế nào để bạn tự động tải một lớp trong Python?

    Đây tải mô -đun hoặc lớp..
    Bằng cách sử dụng phương thức __Import __ (): __Import __ () là một phương thức dunder (Phương pháp bắt đầu và kết thúc với Double Undercore cũng được gọi là Phương pháp ma thuật) và tất cả các lớp sở hữu nó. ....
    Sử dụng mô -đun IMP: Các mô -đun có thể được nhập động bằng mô -đun IMP trong Python ..

    Làm thế nào để bạn nhập một lớp trong Python?

    Nhập một lớp cụ thể bằng cách sử dụng lệnh nhập mà bạn chỉ cần tạo một lớp khác. Tệp PY giống như myfile.py và biến lớp học của bạn. Sau đó, trong tệp chính chỉ cần nhập lớp bằng dòng lệnh từ hình vuông nhập khẩu myfile.in the main file just import the class using the command line from MyFile import Square.

    __ nhập __ làm gì trong Python?

    __Import __ () trong mô -đun Python giúp đưa mã có mặt trong một mô -đun khác bằng cách nhập hàm hoặc mã hoặc tệp bằng cách nhập phương thức Python.Nhập trong Python trả về đối tượng hoặc mô -đun mà chúng tôi đã chỉ định trong khi sử dụng mô -đun nhập.helps in getting the code present in another module by either importing the function or code or file using the import in python method. The import in python returns the object or module that we specified while using the import module.

    __ tất cả __ trong Python là gì?

    Python __all__ Đó là danh sách các đối tượng công khai của mô -đun đó, như được giải thích bằng nhập *.Nó ghi đè mặc định che giấu mọi thứ bắt đầu bằng một dấu gạch dưới.a list of public objects of that module, as interpreted by import * . It overrides the default of hiding everything that begins with an underscore.