The static Object-oriented methods, class methods

Sometimes the need to create objects by selective conditions, you can use a static class method or methods to achieve the purpose.
 
1 static method @staticmethod
Before, we define a method in the class is an object method, that these methods are sending a message to the object. In fact, we write in the process does not require class are object method, for example, we define a "triangle" classes, methods to construct three sides of the triangle passing through the length and circumference calculated to provide, but the incoming three side length may not be able to construct a triangle object, so we could start with a way to verify whether the three side lengths can form a triangle, it is clear that this method is not an object method, because the triangular object when calling this method has not been created out (because none We can not know the three sides constituting a triangle), so this method belongs to the triangle-like object and are not part of the triangle. You can use static methods to solve such problems.
 
class Triangle(object):
 
    def __init__(self, a, b, c):
       self._a = a
       self._b = b
       self._c = c
 
    @staticmethod
    def is_valid(a, b, c):
       return a + b > c and b + c > a and a + c > b
 
    def perimeter(self):
       return self._a + self._b + self._c
 
def main(a,b,c):
    if Triangle.is_valid(a, b, c)==True:
       t = Triangle(a, b, c)
       print ( 'perimeter of the triangle:% s'% t.perimeter ())
    else:
       print ( 'can not form a triangle.')
 
if __name__ == '__main__':
    main(3,4,5)
    main(1,2,3)
 
 
 
Method @classmethod Class 2
And more similar to the static method, Python can also agree in the first parameter defined in the class class methods, class methods named cls, it represents the current class of objects related information (class itself is a target, and some places metadata object called a class), this parameter we can get information and related classes and create objects out of class.
 
class Triangle(object):
 
    def __init__(self, a=0, b=0, c=0):
       self._a = a
       self._b = b
       self._c = c
 
    @classmethod
    def is_valid(cls):
       return cls(a,b,c)
 
    def perimeter(self):
       return self._a + self._b + self._c
 
def main(a,b,c):
    if  a+ b > c and b + c > a and a + c > b:
       t= Triangle.is_valid()
       print ( 'perimeter of the triangle:% s'% t.perimeter ())
    else:
       print ( 'can not form a triangle.')
 
if __name__ == '__main__':
    main(3,4,5)
    main(1,2,3)
 
 
 
The same output:
Perimeter of the triangle: 12
Can not form a triangle.
 
 

Guess you like

Origin www.cnblogs.com/myshuzhimei/p/11767360.html