Python Detailed class method: Instance method, class method, static method (c) __python

Source: Internet
Author: User
Tags class definition instance method

1 . The first argument of an instance method instance method must be "self", and the instance method can only be invoked through a class instance, at which point "Self" represents the instance itself . the properties of an instance can be accessed directly through "self" .

class Person (object):
    tall = 180
    Hobbies = []
    def __init__ (self, Name, age,weight):
        self.name = name
        Self.age = age
        self.weight = weight
    def infoma (self):
        print ('%s '%s weights%s '% (Self.name, self.age,self.weight))


Bruce = Person ("Bruce", 25,180)
Bruce.infoma ()

Bruce is weights 180


2. Class method class methods use the CLS as the first parameter , theCLS represents the class itself , and the @classmethod adorner is defined. The CLS can access the related properties of the class.

class Person (object):

    tall = 180
    Hobbies = []
    def __init__ (self, Name, age,weight):
        self.name = name
        Self.age = age
        self.weight = weight
    @classmethod     #类的装饰器
    def infoma (CLS):   #cls表示类本身, Use the class parameter CLS
        print (cls.__name__)
        print (dir (CLS))
#cls表示类本身
person.infoma ()  # to call the adorner function of the class directly, The CLS can access the related properties of a class
Bruce = Person ("Bruce", 25,180)   #也可以通过两步骤来实现, the first instance of the person is instantiated, and the second step is to invoke the adorner

person[' __class__ ', ' __delattr__ ', ' __dict__ ', ' __dir__ ', ' __doc__ ', ' __eq__ ', ' __format__ ', ' __ge__ ', ' __getattribute __ ', ' __gt__ ', ' __hash__ ', ' __init__ ', ' __le__ ', ' __lt__ ', ' __module__ ', ' __ne__ ', ' __new__ ', ' __reduce__ ', ' __reduce_ex __ ', ' __repr__ ', ' __setattr__ ', ' __sizeof__ ', ' __str__ ', ' __subclasshook__ ', ' __weakref__ ', ' hobbies ', ' infoma ', ' tall ' ]

person[' __class__ ', ' __delattr__ ', ' __dict__ ', ' __dir__ ', ' __doc__ ', ' __eq__ ', ' __format__ ', ' __ge__ ', ' __getattribute __ ', ' __gt__ ', ' __hash__ ', ' __init__ ', ' __le__ ', ' __lt__ ', ' __module__ ', ' __ne__ ', ' __new__ ', ' __reduce__ ', ' __reduce_ex __ ', ' __repr__ ', ' __setattr__ ', ' __sizeof__ ', ' __str__ ', ' __subclasshook__ ', ' __weakref__ ', ' hobbies ', ' infoma ', ' tall ' ]

3, static method and instance method and class method are different, static method has no parameter limit, need neither instance parameter, nor need class parameter, use @staticmethod adorner when defining. Like similar methods, static methods can be accessed through class names or through instances.

class Person (object):

    tall = 180
    Hobbies = []
    def __init__ (self, Name, age,weight):
        self.name = name
        Self.age = age
        self.weight = weight
    @staticmethod    #静态方法装饰器
    def infoma ():     #没有参数限制, no instance arguments, Also use the class parameter
        print (Person.tall)
        print (person.hobbies)
#person. Infoma ()   #静态法可以通过类名访问
Bruce = Person ("Bruce", 25,180)   #通过实例访问

static method, class method use difference or use scene

1. Class methods are used in simulating Java to define multiple constructors.
Because there can be only one initialization method in a Python class, you cannot initialize the class in different situations.
Reference Django Https://docs.djangoproject.com/en/1.9/ref/models/instances/
Take a look at the code below.

# Coding:utf-8


class Book (object):

    def __init__ (self, title):
        self.title = title

    @classmethod
    DEF create (CLS, title): Book
        = CLS (title=title) return book

book1 = Book ("Python")
Book2 = Book.create ( "Python and Django")
print (book1.title)
print (Book2.title)
In particular, static methods can also achieve the above function, when the static method each time to write the name of the class, inconvenient.

2, the static method method in the class calls the static method.
The following code, the static method calls another static method, and if the static method is invoked instead of a class method, the CLS can be substituted for the class.

Make the code look a little leaner. Also prevents the class name from being modified without modifying the original class name in the class definition.

# Coding:utf-8


class Foo (object):
    X = 1
    Y = 2

    @staticmethod
    def averag (*mixes): Return
        sum ( MIXES)/Len (mixes)

    @staticmethod
    def static_method (): Return
        Foo.averag (foo.x, foo.y)

    @classmethod
    def Class_method (CLS): Return
        Cls.averag (CLS. X, CLS. Y)

foo = foo ()
print (Foo.static_method ())
print (Foo.class_method ())

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.