The examples in this article describe Python static methods. Share to everyone for your reference.
The implementation method is as follows:
The code is as follows:
Staticmethod Found at: __builtin__
Staticmethod (function), method
Convert a function to is a static method.
A static method does not receive an implicit first argument.
To declare a static method with this idiom:
Class C:
def f (arg1, arg2, ...): ...
f = Staticmethod (f)
It can called either on the class (e.g. C.F ()) or in an
Instance
(e.g. C (). f ()). The instance is ignored except for its class.
Static methods in Python is 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 # of Employees created
Maxemployees = ten # maximum number of comfortable employees
Def iscrowded ():
"" "Static method returns True if the employees is 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 is crowded?",
Print answers[employee.iscrowded ()]
Print "\ncreating objects of class Employee ..."
# Create one objects of class Employee
For I in range (11):
Employeelist.append (Employee ("John", "Doe" + str (i)))
# call static method using object
Print "Employees is crowded?",
Print answers[employeelist[i].iscrowded ()]
Print "\nremoving One employee ..."
Del employeelist[0]
Print "Employees is crowded?", answers[employee.iscrowded ()]
if __name__ = = "__main__":
Main ()
Hopefully this article will help you with Python programming.