decorator - What's the difference to use @staticmethod and global function in Python? -
decorator - What's the difference to use @staticmethod and global function in Python? -
i have read
what difference between @staticmethod , @classmethod in python? python @classmethod , @staticmethod beginner?as staticmethod
can't access instance of class, don't know what's difference betweent , global function
?
and when should utilize staticmethod
? can give example?
like global function, static method cannot access instance of containing class. conceptually belongs containing class. other benefit can avoid name confliction.
when function designed serve given class, it's advisable create static method of class. called cohesion. besides, if function not used outside, can add together underscore before mark "private", called information hiding(despite python doesn't back upwards private methods). rule of thumb, exposing little interfaces possible create code more clean , less subject change.
even if function supposed serve shared utility many classes across multiple modules, making global function still not first choice. consider create utility class's static method, or create global function in specialized module. 1 reason collecting similar-purposed functions mutual class or module level's abstraction/modularization(for little projects, people may argue overengineering). other reason may cut down namespace pollution.
python decorator
Comments
Post a Comment