博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python 中的 @staticmethod 和 @classmethod
阅读量:4099 次
发布时间:2019-05-25

本文共 2089 字,大约阅读时间需要 6 分钟。

视频中或者说书中,使用了@staticmethod,先把这个问题解决了。

class Config:   ...    @staticmethod    def 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_blueprint    app.register_blueprint(main_blueprint)    return app

StackOverflow上几个相关的问题:

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).

转载地址:http://mheii.baihongyu.com/

你可能感兴趣的文章
带WiringPi库的交叉笔译如何处理二之软链接概念
查看>>
Java8 HashMap集合解析
查看>>
自定义 select 下拉框 多选插件
查看>>
fastcgi_param 详解
查看>>
poj 1976 A Mini Locomotive (dp 二维01背包)
查看>>
剑指_复杂链表的复制
查看>>
MODULE_DEVICE_TABLE的理解
查看>>
No devices detected. Fatal server error: no screens found
查看>>
db db2_monitorTool IBM Rational Performace Tester
查看>>
postgresql监控工具pgstatspack的安装及使用
查看>>
【JAVA数据结构】双向链表
查看>>
【JAVA数据结构】先进先出队列
查看>>
谈谈加密和混淆吧[转]
查看>>
乘法逆元
查看>>
Objective-C 基础入门(一)
查看>>
通过mavlink实现自主航线的过程笔记
查看>>
Flutter Boost的router管理
查看>>
Vue2.0全家桶仿腾讯课堂(移动端)
查看>>
React+Redux系列教程
查看>>
19 个 JavaScript 常用的简写技术
查看>>