python有静态方法吗_Python静态方法,为什么?

关于类中的staticmethods,我有一些问题。我先举个例子。在

示例一:class Static:

def __init__(self, first, last):

self.first = first

self.last = last

self.age = randint(0, 50)

def printName(self):

return self.first + self.last

@staticmethod

def printInfo():

return "Hello %s, your age is %s" % (self.first + self.last, self.age)

x = Static("Ephexeve", "M").printInfo()

输出:

^{pr2}$

例二:class Static:

def __init__(self, first, last):

self.first = first

self.last = last

self.age = randint(0, 50)

def printName(self):

return self.first + self.last

@staticmethod

def printInfo(first, last, age = randint(0, 50)):

print "Hello %s, your age is %s" % (first + last, age)

return

x = Static("Ephexeve", "M")

x.printInfo("Ephexeve", " M") # Looks the same, but the function is different.

输出Hello Ephexeve M, your age is 18

我知道我不能打电话给任何人自我属性在staticmethods中,我只是不太确定何时以及为什么要使用它。在我看来,如果您创建一个具有几个属性的类,也许您希望以后使用它们,而不是拥有一个所有属性都不可调用的staticmethod。

有人能解释一下吗?Python是我的第一种编程语言,所以如果在Java中也是这样,我不知道。在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值