gpt4 book ai didi

python - Django Rest 框架和@staticmethod。它有什么好处呢?

转载 作者:行者123 更新时间:2023-11-30 22:07:24 25 4
gpt4 key购买 nike

我正在使用 PyCharm 在serializers.py 中编写一些方法。然后我必须编写一个方法来获取名称。

 def get_artist_name(obj):
return obj.artist.name

然后 PyCharm 建议我将该方法设为静态。

 @staticmethod
def get_artist_name(obj):
return obj.artist.name

从那时起我就想知道它有什么好处?这是一个很好的做法还是类似的事情?如果有任何我可以阅读的有关此特定主题的文档,请提前致谢。

最佳答案

第一个变体是错误的:如果调用实例方法,第一个参数是被调用者(x中的x.method(para, meter))。所以这意味着你需要这样写:

def get_artist_name(<b>self,</b> obj):
return obj.artist.name

让它正常工作,如documentation of a SerializerMethodField 中所示.

但是,由于您不使用 self在函数体中,使用 self 编写函数是没有用的。范围。此外,不将其设为 @staticmethod ,该函数只能使用序列化器实例正确调用:如果您使用 SerializerClass.get_artist_name(None, obj) 调用它,那么您需要提供第一个未使用的参数。这与使用 some_serializer.get_artist_name(obj) 调用它形成对比,其中只有一个显式参数。

通过使用 @staticmethod ,您“协调”两者:现在您可以调用 SerializerClass.get_artist_name(obj) ,和some_serializer.get_artist_name(obj) ,还有你@staticmethod装饰器,将确保两者以相同的方式工作。

除非您认为需要访问序列化器对象,或者子类需要访问该对象(通常您希望避免从子实现中“删除”装饰器),否则使用 @staticmethod 可能更优雅。 .

关于python - Django Rest 框架和@staticmethod。它有什么好处呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52470386/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com