本文主要是介绍Python 中的 @staticmethod 和 @classmethod,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
视频中或者说书中,使用了@staticmethod
,先把这个问题解决了。
class Config:...@staticmethoddef init_app(app):pass
The reason to use staticmethod is if you have something that could be written as a standalone function (not part of any class), but you want to keep it within the class because it’s somehow semantically related to the class.
这个init_app
函数和Config
类相关,但是本来不用写在Config
类中(没有传递self
参数),可以写成单独的函数。
这里为了使用方便,使用了@staticmethod
装饰器,将init_app
函数写在了Config
类中(可以使用Config.init_app(app)
)。
因为可以当成独立的函数,使用前不需要实例化:
bootstrap = Bootstrap()
mail = Mail()
moment = Moment()
db = SQLAlchemy()def create_app(config_name):app = Flask(__name__)app.config.from_object(config[config_name])config[config_name].init_app(app) # 直接使用了init_app(app)方法bootstrap.init_app(app) #但是这儿init_app(app)方法为空。还是那个bootstrap对象。mail.init_app(app)moment.init_app(app)db.init_app(app)from .main import main as main_blueprintapp.register_blueprint(main_blueprint)return app
StackOverflow
上几个相关的问题:
Meaning of @classmethod and @staticmethod for beginner?
What is the difference between @staticmethod and @classmethod in Python?
Why do we use @staticmethod?
classmethod must have a reference to a class object as the first parameter, whereas staticmethod can have no parameters at all.
另外的解释:
@staticmethod function is nothing more than a function defined inside a class. It is callable without instantiating the class first. It’s definition is immutable via inheritance.
@classmethod function also callable without instantiating the class, but its definition follows Sub class, not Parent class, via inheritance. That’s because the first argument for @classmethod function must always be cls (class).
还有个解释:
@classmethod means: when this method is called, we pass the class as the first argument instead of the instance of that class (as we normally do with methods). This means you can use the class and its properties inside that method rather than a particular instance.
@staticmethod means: when this method is called, we don’t pass an instance of the class to it (as we normally do with methods). This means you can put a function inside a class but you can’t access the instance of that class (this is useful when your method does not use the instance).
这篇关于Python 中的 @staticmethod 和 @classmethod的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!