使用静态方法有什么好处? [英] What is the advantage of using static methods?

查看:42
本文介绍了使用静态方法有什么好处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 python 中遇到了未绑定的方法错误

I ran into unbound method error in python with the code

import random

class Sample(object):
    '''This class defines various methods related to the sample'''

    def drawSample(samplesize,List):
        sample=random.sample(List,samplesize)
        return sample

Choices=range(100)
print Sample.drawSample(5,Choices)

在这里阅读了许多有用的帖子后,我想出了如何在上面添加 @staticmethod 以使代码正常工作.我是一个蟒蛇新手.有人可以解释为什么要定义静态方法吗?或者,为什么不是所有方法都定义为静态方法?

After reading many helpful posts here, I figured how I could add @staticmethod above to get the code working. I am a python newbie. Can someone please explain why one would want to define static methods? Or, why are not all methods defined as static methods?

推荐答案

静态方法的用途有限,因为它们无法访问类的实例的属性(就像常规方法那样),并且它们没有'不能访问类本身的属性(就像类方法那样).

Static methods have limited use, because they don't have access to the attributes of an instance of a class (like a regular method does), and they don't have access to the attributes of the class itself (like a class method does).

所以它们对日常方法没有用.

So they aren't useful for day-to-day methods.

但是,它们可以用于将某些实用程序与类组合在一起 - 例如从一种类型到另一种类型的简单转换 - 除了提供的参数(以及模块的一些全局属性)之外,不需要访问任何信息.

However, they can be useful to group some utility function together with a class - e.g. a simple conversion from one type to another - that doesn't need access to any information apart from the parameters provided (and perhaps some attributes global to the module.)

它们可以放在班级之外,但在它们只适用于班级的情况下将它们分组在班级内可能是有意义的.

They could be put outside the class, but grouping them inside the class may make sense where they are only applicable there.

您也可以通过实例或类而不是模块名称来引用该方法,这可能有助于读者理解该方法与哪个实例相关.

You can also reference the method via an instance or the class, rather than the module name, which may help the reader understand to what instance the method is related.

这篇关于使用静态方法有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆