Deep Learning

Deep Learning Python Basics — Classes and Modules

Deep Learning Python Basics — functions, classes, and modules

Park

Park

Deep Learning

Written on

Share
Deep Learning Python Basics — Classes and Modules

Example directory structure

.
├── __init__.py
├── base
│   ├── __init__.py
│   ├── data_format.py
│   ├── mnn_forward_base.py
│   └── mnn_net.py
├── lib
│   ├── __init__.py
│   ├── bbox_transform.py
│   ├── blob.py
│   ├── mean_face.py
│   ├── mnn_face.py
│   ├── mnn_face_allign.py
│   ├── mnn_face_det.py
│   └── nms_wrapper.py
├── main.py
├── requirements.txt
└── version.json

Directories and Modules (package)

Adding an __init__.py file to a directory marks that directory as a package, and you can import modules with the import keyword.

Main uses

  1. Mark a directory as a package: When a directory contains an __init__.py file, the Python interpreter treats it as a package that can contain modules or subpackages.

  2. Initialize package contents: You can define initialization code in __init__.py that runs before any module in the package is imported.

  3. Define package-level variables and functions: Through __init__.py, you can define shared variables, functions, or classes for use by other modules in the package.

  4. Control package import behavior: In __init__.py, you can import other modules in the package to control import order, or make importing the package automatically load certain modules.

  5. Support from package import *: If __all__ is defined in __init__.py, you can use import * from the package to import specified modules or objects.


Example code

class MNNFacePlayground(DebugUIBaseClass): 
  def __init__(self):
      #create global net
      self.global_net = MNNFace(det_model_path, allign_model_path)

  def process(self, type, id, batch_data):
      # ...

  @staticmethod
  def convertInputImageToRGB(input_data, data_format):
      #...

  def __del__(self):
      print "End"

  @classmethod
  def init(cls):
      global ins = cls()
      
if __name__ == '__main__':
   MNNFacePlayground.init()   

The pass Keyword

pass is a keyword in Python. It is a no-op that does nothing and is usually used as a placeholder or in control-flow structures to represent an empty statement.

Example:

  def process(self, batch_data):
        pass

The global Keyword

The global keyword in Python declares a global variable. Specifically:

  • Purpose: Using global lets you modify a variable in the global scope from inside a function.
  • Usage: Declare a variable as global inside a function so it refers to and can modify the same-named variable defined outside the function.

Example:

x = 5

def test():
    global x
    x = 10  # Modify the global variable x

test()
print(x)  # Output 10

The def __init__(self): Method

__init__ is a special method in Python classes, also called a magic method. Its name is fixed and must be __init__. This method is mainly used to initialize a class instance when it is created. Although the name is fixed, it is very important for ensuring instances are initialized correctly.

Summary: Similar in role to a C++ constructor.

The def __del__(self): Method

This function is the destructor in a Python class. Its behavior is:

  1. Called automatically when an object is destroyed, usually for cleanup such as closing files or releasing resources.
  2. Cannot return any value, and no return value is needed.
  3. May not always be called, because Python's garbage collector may destroy objects at any time.

Summary: Similar in role to a C++ destructor.

The @staticmethod Decorator

Typically, @staticmethod defines a static method in a class that does not need to access or modify class state. Static methods are independent of class instances, so self is not passed when they are called.

Example:

@staticmethod
def convertInputImageToRGB(input_data, data_format):
  # func body, do something...

The @classmethod Decorator

@classmethod is a decorator used to define a class method. The first parameter of a class method is usually cls, representing the class itself rather than an instance.

Example:

@classmethod
def init(cls):
    ins = cls() # Create an instance of the cls class

The main differences between @classmethod and @staticmethod are their first parameter and purpose:

  • classmethod:
    • The first parameter is usually cls, representing the class object.
    • Can access or modify class state.
  • staticmethod:
    • Has no default first parameter.
    • Does not automatically receive the class or instance as the first argument.
    • Usually used for helper functionality unrelated to class state.

In short, @classmethod is tied directly to the class and can operate on class variables; @staticmethod is more like an ordinary function that happens to live inside a class.

The __main__ Built-in Variable

The role of __name__ == '__main__' is:

  1. __name__ is a built-in Python variable. When a file is imported as a module, its value is the module name.
  2. When a file is run directly, __name__ has the value '__main__'.
  3. With this check, you can decide which code runs when the file is executed directly but not when it is imported as a module, avoiding code conflicts.

The self Parameter

self is the first parameter passed to the __init__ method. It represents the instance itself, allowing instance methods to access and operate on the class's attributes and methods. In Python, self is conventionally the first parameter name in instance methods, but you do not pass it explicitly when calling the method.