Staticmethod static methods and class methods classmethod

Staticmethod static methods and class methods classmethod

 

First, the class method classmethod

  • The method becomes a method of a class, this method can be directly used to invoke class, need not rely on any of the objects, i.e., do not need to instantiate some changes may be made
  • When this method of operation involves only static property, you should use this method to decorate classmethod
class Goods:
     __discount = 0.8   # static private attributes 
    DEF  the __init__ (Self, name, price): 
        the self.name = name 
        Self. __price = price   # price privatization 
    @Property   # The price attribute disguised method, direct call function outside the class, Some operations performed private attributes 
    DEF . price (Self):   # do not pass parameters 
        return Self. __price * Goods. __discount 
    @classmethod   # the way into a class method, this method can be invoked directly on the outer class-based, rather than We need to rely on any object that can not be instantiated 
    DEF change_discount (CLS, NEW_DISCOUNT):   # modify discount
        CLS. __discount = NEW_DISCOUNT 
apple = Goods ( ' apple ' , 5)   # Example of 
Print (apple.price) 
Goods.change_discount ( 0.5)   # here may be directly used to invoke Goods category, you do not need to call relying on apple 
Print (apple. price)

operation result:

4.0
2.5

 

Second, the static method staticmetho

  • In the fully object-oriented programming, if a relationship is not a function of both objects and classes and also does not matter, then use this function staticmethod will become static method
class the Login:
     DEF  __init__ (Self, name, password): 
        self.name = name 
        self.pwd = password
     DEF the Login (Self): Pass 
    @staticmethod 
    DEF get_usr_pwd ():   # Here you can pass parameters, but not the specific parameters, Some common parameter 
        # originally functions methods and classes and objects have nothing to do, but now is the class static methods of the 
        usr = the INPUT ( ' user name: ' ) 
        pwd = the INPUT ( ' password: ' ) 
        the Login (usr, pwd ) 
Login.get_usr_pwd ()   # use the class directly to the static method call

 

III Summary

  • , Can not be instantiated class methods and static methods are called directly by the class can do related operations
  • Objects can also call the class methods and static methods (pointer to class), but generally recommended to use the class name calling
  • Class method has a default parameter cls, on behalf of the class
  • Static methods do not default parameters, like a function

 

Guess you like

Origin www.cnblogs.com/wxm422562/p/11086690.html