哈里发王国传奇,雨在风中吉他谱,wmsyspr9.prx
本文实例讲述了python静态方法。分享给大家供大家参考。
具体实现方法如下:
staticmethod found at: __builtin__
staticmethod(function) -> method
convert a function to be a static method.
a static method does not receive an implicit first argument.
to declare a static method, use this idiom:
class c:
def f(arg1, arg2, ...): ...
f = staticmethod(f)
it can be called either on the class (e.g. c.f()) or on an
instance
(e.g. c().f()). the instance is ignored except for its class.
static methods in python are similar to those found in
java or c++.
for a more advanced concept, see the classmethod builtin.
class employee:
"""employee class with static method iscrowded"""
numberofemployees = 0 # number of employees created
maxemployees = 10 # maximum number of comfortable employees
def iscrowded():
"""static method returns true if the employees are crowded"""
return employee.numberofemployees > employee.maxemployees
# create static method
iscrowded = staticmethod(iscrowded)
def __init__(self, firstname, lastname):
"""employee constructor, takes first name and last name"""
self.first = firstname
self.last = lastname
employee.numberofemployees += 1
def __del__(self):
"""employee destructor"""
employee.numberofemployees -= 1
def __str__(self):
"""string representation of employee"""
return "%s %s" % (self.first, self.last)
# main program
def main():
answers = [ "no", "yes" ] # responses to iscrowded
employeelist = [] # list of objects of class employee
# call static method using class
print "employees are crowded?",
print answers[ employee.iscrowded() ]
print "\ncreating 11 objects of class employee..."
# create 11 objects of class employee
for i in range(11):
employeelist.append(employee("john", "doe" + str(i)))
# call static method using object
print "employees are crowded?",
print answers[ employeelist[ i ].iscrowded() ]
print "\nremoving one employee..."
del employeelist[ 0 ]
print "employees are crowded?", answers[ employee.iscrowded() ]
if __name__ == "__main__":
main()
希望本文所述对大家的python程序设计有所帮助。
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!!
点击进行留言回复
相关文章:
-
-
python如何查看网页代码
用python查看网页代码的方法:1、使用“import”导入requests包import requests2、使用requests包的get()函数通过网页...
[阅读全文]
-
-
python如何保存文本文件
python保存文本文件的方法:使用python内置的open()类可以打开文本文件,向文件里面写入数据可以用write()函数,写完之后,使用close()函...
[阅读全文]
-
python如何编写win程序
python可以编写win程序。win程序的格式是exe,下面我们就来看一下使用python编写exe程序的方法。编写好python程序后py2exe模块即可将...
[阅读全文]
-
-
-
-
-
-
网友评论