您的位置:首页 > 编程语言 > Python开发

Python 中的 @staticmethod 和 @classmethod

2017-09-18 15:36 363 查看
视频中或者说书中,使用了
@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
上几个相关的问题:

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 flask