Python 中的 @staticmethod 和 @classmethod

124 篇文章 0 订阅

视频中或者说书中,使用了@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).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值