Analysis of instance methods static methods class methods class variables and instance variables in python

  • 2020-04-02 13:39:58
  • OfStack

Note: Python2.7 is used.

I. instance method

An instance method is a method that an instance of a class can use. As follows:


class Foo:
    def __init__(self, name):
        self.name = name
    def hi(self):
        print self.name
if __name__ == '__main__':
    foo01 = Foo('letian')
    foo01.hi()
    print type(Foo)
    print type(foo01)
    print id(foo01)
    print id(Foo)

The running result is:

letian
<type 'classobj'>
<type 'instance'>
40124704
31323448[code]
 As you can see, Foo the type for classobj (class object, python The class itself is also an object. foo01 the type for instance (example). while hi() It's an instance method, so foo01.hi() Will be output 'letian' . The first parameter of the instance method defaults to self , denoting an instance. self Not a keyword, but a convention. init() Is the instance method that is called by default when an instance is generated. will Foo Change the definition to the following form: 
[code]class Foo:
    def __init__(this, name):
        this.name = name
    def hi(here):
        print here.name

It still works correctly. The built-in function id is used to view the identifier of the object. The doc content is as follows:

>>> print id.__doc__
id(object) -> integer
Return the identity of an object.  This is guaranteed to be unique among
simultaneously existing objects.  (Hint: it's the object's memory address.)

Two, the static method

A static method is a normal function that sits in the namespace of a class definition and does not operate on any instance type. Use the decorator @staticmethod to define static methods. Class objects and instances can call static methods:


class Foo:
    def __init__(self, name):
        self.name = name
    def hi(self):
        print self.name
    @staticmethod
    def add(a, b):
        print a + b
if __name__ == '__main__':
    foo01 = Foo('letian')
    foo01.hi()
    foo01.add(1,2)
    Foo.add(1, 2)


      The operation results are as follows:


letian
3
3

Note that many programming languages do not allow instances to invoke static methods.

Class methods

A class method is a method that operates on the class itself as an object. Class methods are defined using the @classmethod decorator, whose first parameter is the class, and the convention is written as CLS. Class objects and instances can invoke class methods:


class Foo:
    name = 'letian '
    @classmethod
    def hi(cls, x):
        print cls.name * x
if __name__ == '__main__':
    foo01 = Foo()
    foo01.hi(2)
    Foo.hi(3)

The operation results are as follows:

letian letian 
letian letian letian

Note that many other programming languages do not allow instances to invoke class methods.

Fourth, the super

Super is used to execute functions in the parent class, for example:


class Foo(object):
    def hi(self):
        print 'hi,Foo'
class Foo2(Foo):
    def hi(self):
        super(Foo2, self).hi()
if __name__ == '__main__':
    foo2 = Foo2()
    foo2.hi()

Operation results:

hi,Foo

Note that the Foo class must inherit from a class (and the inheritance chain starts with the object class), otherwise an error is reported. If changed to the following form:

class Foo:
    def hi(self):
        print 'hi,Foo'
class Foo2(Foo):
    def hi(self):
        super(Foo2, self).hi()
if __name__ == '__main__':
    foo2 = Foo2()
    foo2.hi()

The error of operation times is as follows:

......
TypeError: must be type, not classobj

About super, specific please see http://docs.python.org/2/library/functions.html? Highlight =super#super and super.doc.


Class variables and instance variables

Class variables are defined after the class definition, and instance variables start with self. Such as:


class Foo(object):
    val = 0
    def __init__(self):
        self.val = 1
if __name__ == '__main__':
    foo = Foo()
    print foo.val
    print Foo.val

The running result is:

1
0

The instance can also access the class variables, as follows:

class Foo(object):
    val = 0
    def __init__(self):
        pass
if __name__ == '__main__':
    foo = Foo()
    print foo.val
    print Foo.val

The operation results are as follows:

0
0

In addition, class variables can be accessed by:

class Foo(object):
    val = 3
    def __init__(self):
        print self.__class__.val
if __name__ == '__main__':
    foo = Foo()

Operation results:

3

Here's another way:

class Foo(object):
    val = 3
    def __init__(self):
        pass
    @classmethod
    def echo(cls):
        print cls.val
if __name__ == '__main__':
    Foo.echo()

Operation results:
The same code at the page code block index 16

How to call the constructor of the superclass

Subclasses (derived classes) do not automatically call the parent (base class) init method, for example:


class Foo(object):
    def __init__(self):
        self.val = 1
class Foo2(Foo):
    def __init__(self):
        print self.val
if __name__ == '__main__':
    foo2 = Foo2()

Run times error.

There are two ways to call the superclass init method. The first is:


class Foo(object):
    def __init__(self):
        self.val = 1
class Foo2(Foo):
    def __init__(self):
        Foo.__init__(self)
        print self.val
if __name__ == '__main__':
    foo2 = Foo2()

The second:

class Foo(object):
    def __init__(self):
        self.val = 1
class Foo2(Foo):
    def __init__(self):
        super(Foo2,self).__init__()
        print self.val
if __name__ == '__main__':
    foo2 = Foo2()

The operation results of these two methods are:

1

But there is a difference.


Related articles: