在python中,下面有什么区别,哪个更好
发布时间:2020-12-20 13:37:35 所属栏目:Python 来源:网络整理
导读:参见英文答案 What is the difference between @staticmethod and @classmethod?????????????????????????????????????23个 我写了这样的代码,它们都适合我,但有什么区别?哪个更好? class Demo1(object): def __init__(self): self.attr = self._make_attr
参见英文答案 >
What is the difference between @staticmethod and @classmethod?????????????????????????????????????23个
我写了这样的代码,它们都适合我,但有什么区别?哪个更好? class Demo1(object): def __init__(self): self.attr = self._make_attr() def _make_attr(self): #skip... return attr class Demo2(object): def __init__(self): self.attr = self._make_attr() @staticmethod def _make_attr(): #skip... return attr 解决方法
如果两者都有效,则意味着在make_attr中你没有使用self.
使它成为一个常规的非静态方法只有在代码可以在逻辑上依赖于实例并且在当前实现中偶然不依赖于它时才有意义(但是例如它可能依赖于从该类派生的类中的实例) ). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |