Class methods, static methods, object methods in Python

Source: Internet
Author: User

Note: The following are public-premise, private methods can only be called inside the class, do not need to speak more.

1. Object methods

This method has a default parameter: Self, which represents the object of the instance

    def __init__ (self):         Print (" Initialize object ")

Class is not a direct call to an object method:

class User (object):     ' ZS '    def __init__ (self):         Print (" Initialize object ") of User. __init__ ()

This call throws an error: TypeError: __init__ () Missing 1 required positional argument: ' Self '

2. Class methods

The class method, as the name implies, can be called directly from the class name, or by an object instantiated by the class.

classUser (object): Name='ZS'    __pass= 1223def __init__(self):Print("Initializing Objects") @classmethod#Decorator    def changeName1(CLS): Cls.name='ls'        Print("method%s for class"% (CLS.__pass))

ChangeName1 is a class method, preceded by a decorator: @classmethod, and has a default parameter, the CLS is the class itself.

3. Static method

In fact, static methods can be understood as a special class method, which differs from the normal class method in two points:

(1) Different modifiers

(2) No default parameters

The rest is identical to the class method.

classUser (object): Name='ZS'    __pass= 1223def __init__(self):Print("Initializing Objects") @classmethod#Decorator    defchangeName1 (CLS): Cls.name='ls'        Print("method%s for class"% (CLS.__pass)) @staticmethoddefchangeName2 (): User.Name='ww'        Print("Static Methods") U=User () u.changename1 () user.changename1 () u.changename2 () user.changename2 ()

Summary: An object instantiated by a class can invoke all public methods inside the class, and the class can only invoke the class method and the static method (if it is a private method, it can only be called inside the class. )

Class methods, static methods, object methods in Python

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.