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
(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__”:


Posted in 未分类