python-static method Staticmethod, class method Classmethod, Attribute Method property

Source: Internet
Author: User
Tags instance method python decorator

Python has 3 main methods, namely static methods (Staticmethod), class methods (Classmethod), and instance methods.

12345678910111213141516 deffoo(x):    print"executing foo(%s)"%(x) classA(object):    deffoo(self,x):        print"executing foo(%s,%s)"%(self,x)     @classmethod    defclass_foo(cls,x):        print"executing class_foo(%s,%s)"%(cls,x)     @staticmethod    defstatic_foo(x):        print"executing static_foo(%s)"%x a=A()

The self and the CLS are bindings to classes or instances, which we can call for general functions, which are foo(x) most commonly used, and whose work has nothing to do with anything (classes, instances). For instance methods, we know that we need to bind this instance every time we define a method in a class, that is foo(self, x), why do you do this? Because the invocation of the instance method is inseparable from the instance, we need to pass the instance to the function, which is a.foo(x) called when (In fact foo(a, x) ). class method, except that it passes a class instead of an instance A.class_foo(x) . Note that the self and the CLS here can replace the other parameters, but the Python convention is these two, or do not change the good.

For static methods, like normal methods, there is no need to bind to who, the only difference is that the call needs to be used a.static_foo(x) or A.static_foo(x) called.

\ instance Method class Method Static Methods
A = A () A.foo (x) A.class_foo (x) A.static_foo (x)
A Not available A.class_foo (x) A.static_foo (x)

Common methods of Class

class Animal(object):    def __init__(self,name): self.name = name def intro(self): print(‘there is a %s‘%(self.name))cat = Animal(‘cat‘)cat.intro()
    • Static class methods
class Animal(object):    def __init__(self,name): self.name = name @staticmethod def intro(self): print(‘there is a %s‘%(self.name))cat = Animal(‘cat‘)cat.intro()
    • Adding an adorner will result in an error, because the method becomes a normal function, detached from the relationship to the class, and cannot reference the variables in the constructor.

Examples of using scenarios: Python's methods in the built-in method OS, which can be used directly by the toolkit, do not matter with the class.

class Animal(object):    def __init__(self,name): self.name = name @classmethod def intro(self): print(‘there is a %s‘%(self.name))cat = Animal(‘cat‘)cat.intro()
    • Error message

If you replace

class Animal(object):    name = ‘cat‘ def __init__(self,name): self.name = name @classmethod def intro(self): print(‘there is a %s‘%(self.name))cat = Animal(‘cat‘)cat.intro()
    • can run correctly.

Conclusion: Class methods can only call class variables and cannot invoke instance variables

The @property property method turns a method into a (disguised) class property. Because the nature of a class property is a class variable, the user can modify the variable by invoking the variable. Static methods are used to restrict user behavior for certain scenarios.
@property is widely used in the definition of a class, allowing the caller to write short code while guaranteeing the necessary checks on the parameters, thus reducing the likelihood of errors when the program runs. (from Liaoche's blog)

class Animal(object):    def __init__(self,name): self.name = name @property def intro(self,food): print(‘there is a %s eating %s‘%(self.name,food))cat = Animal(‘cat‘)cat.intro()
    • Error:

    • Method cannot be called normally. If you want to call, the following:
cat.intro
    • In this case, there is no way to pass in the parameters individually. If you want to pass in a parameter, as follows:
class animal def __init__ (self,name): self.name = name  @property def  Intro ' There is a%s eating%s '% (Self.name,food)) Span class= "Hljs-decorator" > @intro. Setter def intro (Self,food): passcat = Animal ( ' cat ') Cat.intro            
    • Cat.intro There are other operations getter Deleter and so on.
One: The Staticmethod code is as follows:
Class Singleton (object):    instance = None    def __init__ (self):        raise SyntaxError (' Can not instance, please Use Get_instance ')    @staticmethod    def get_instance ():        if Singleton.instance is None:            Singleton.instance = object.__new__ (Singleton)        return singleton.instancea = Singleton.get_instance () b = Singleton.get_instance () print (' A id= ', ID (a)) print (' B id= ', ID (b))
The main point of this method is to throw an exception in __init__, prohibit it from being instantiated through a class, only get the instance through a static get_instance function, because it cannot be instantiated by a class, so the static get_instance function can be object.__new__ by the parent class. to instantiate. Two: Classmethod and method A similar, code:
Class Singleton (object):    instance = None    def __init__ (self):        raise SyntaxError (' Can not instance, please Use Get_instance ')    @classmethod    def get_instance (CLS):        If Singleton.instance is None:            Singleton.instance = object.__new__ (Singleton)        return singleton.instancea = Singleton.get_instance () b = Singleton.get_instance () print (' A id= ', ID (a)) print (' B id= ', ID (b))
The main point of this method is to throw an exception in __init__, prohibit it from being instantiated through a class, only get the instance through a static get_instance function, because it cannot be instantiated by a class, so the static get_instance function can be object.__new__ by the parent class. to instantiate. Three: Class property methods and methods like, code:
Class Singleton (object):    instance = None    def __init__ (self):        raise SyntaxError (' Can not instance, please Use Get_instance ')    def get_instance ():        if Singleton.instance is None:            singleton.instance = object.__ new__ (Singleton)        return singleton.instancea = Singleton.get_instance () b = Singleton.get_instance () print (ID (a)) Print (ID (b))
The main point of this method is to throw an exception in __init__, prohibit it from being instantiated through a class, only get the instance through a static get_instance function, because it cannot be instantiated by a class, so the static get_instance function can be object.__new__ by the parent class. to instantiate. Four: __new__

The common method, the code is as follows:

Class Singleton (object):    instance = None    def __new__ (CLS, *args, **kw):        if not cls.instance:            # Cls.instance = object.__new__ (CLS, *args)            cls.instance = Super (Singleton, CLS). __new__ (CLS, *args, **kw)        return cls.instancea = Singleton () b = Singleton () print (ID (a)) print (ID (b))

Five: Decorator

The code is as follows:

def Singleton (CLS):    instances = {}    def getinstance ():        If CLS not in instances:            instances[cls] = CLS () C10/>return Instances[cls]    return getinstance@singletonclass MyClass:    Passa = MyClass () b = MyClass () c = MyClass () Print (ID (a)) print (ID (b)) Print (ID (c))

VI: Meta-class Python2 version:
Class Singleton (Type):    def __init__ (CLS, name, bases, DCT):        super (Singleton, CLS). __INIT__ (name, bases, DCT)        cls.instance = None    def __call__ (CLS, *args):        if Cls.instance is None:            cls.instance = Super (Singleton, CLS). __call__ (*args)        return Cls.instanceclass MyClass (object):    __metaclass__ = Singletona = MyClass () b = MyClass () c = MyClass () print (ID (a)) print (ID (b)) Print (ID (c)) print (A is B) print (A is C)
Or:
Class Singleton (Type):    def __new__ (CLS, name, bases, attrs):        attrs["_instance"] = None        return Super ( Singleton, CLS). __new__ (CLS, name, bases, Attrs)    def __call__ (CLS, *args, **kwargs):        if Cls._instance is None:            cls._instance = Super (Singleton, CLS). __call__ (*args, **kwargs)        return Cls._instanceclass Foo (object):    __metaclass__ = Singletonx = foo () y = foo () print (ID (x)) print (ID (y))
Version Python3:
Class Singleton (Type):    def __new__ (CLS, name, bases, attrs):        attrs[' instance '] = None        return Super ( Singleton, CLS). __new__ (CLS, name, bases, Attrs)    def __call__ (CLS, *args, **kwargs):        if Cls.instance is None:
   cls.instance = Super (Singleton, CLS). __call__ (*args, **kwargs)        return cls.instanceclass Foo (metaclass= Singleton):    PASSX = foo () y = foo () print (ID (x)) print (ID (y))
Seven: The name Overlay code is as follows:
Class Singleton (object):    def foo (self):        print (' foo ')    def __call__ (self):        return Selfsingleton = Singleton () Singleton.foo () A = Singleton () b = Singleton () print (ID (a)) print (ID (b))

python-static method Staticmethod, class method Classmethod, Attribute Method property

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.