Python Static Method Instance and python static instance
This example describes the python static method. Share it with you for your reference.
The specific implementation method is as follows:
Copy codeThe Code is as follows: 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
Instance
(E.g. C (). f (). The instance is ignored before t 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" % (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 ()
I hope this article will help you with Python programming.