Static method of achieving classes in Python

xiaoxiao2021-03-06  48

Topic: In the Python species, the static method of the class is summary.

Method 1: Use __call__eg: import osclass command: class _staticcommand: def __call __ (self): Os.System (Command)

Run = _STATICCOMMAND ()

IF __NAME__ == '__main__': command.run ("Dir / W") #windows command.run ("ls -l") #unix Linux

Realization: Define an internal class (_StaticCommand), an outer class (Command) has a class attribute RUN pointing _StaticCommand instance, the key is the special way to define _StaticCommand __call__, this method is used as _StaticCommand instance use () time Tune, (such as: _StaticCommand () ()), as an instance is a method

Method 2: STATICMETHOD IMPORT OSCLASS COMMAND: DEF RUN (Command): os.system (Command): os.system

Run = staticMethod (RUN) #staticMethod accepts the constructor function reference, at which time RUN becomes the StaticMethod class instance

IF __NAME__ == '__main__': command.run ("Dir / W") #windows command.run ("ls -l") #unix Linux

转载请注明原文地址:https://www.9cbs.com/read-54166.html

New Post(0)