Home  >  Article  >  Backend Development  >  Detailed explanation of classes and types in python

Detailed explanation of classes and types in python

高洛峰
高洛峰Original
2017-03-07 16:41:521312browse

What is a class

can be regarded as a synonym for category or type. All objects belong to a certain class and are called instances of the class.

For example: Bird is an instance of "bird". This is just a general (abstract) class with many subclasses: the bird you see might belong to the subclass "lark". Think of "birds" as the collection of all birds, of which "larks" are a subset. When the class to which an object belongs is a subset of the class to which another object belongs, the former is called a subclass of the latter, so "larks" are subclasses of "birds" and "birds" are "larks" The superclass of "Bird"

Defining a subclass is just a process of defining more methods

Creating a class

>>> class Person:
    def setName(self,name):
        self.name=name
    def getName(self):
        return self.name
    def greet(self):
        print "Hello,world! I'm %s" % self.name

        
>>> foo=Person()
>>> bar=Person()
>>> foo.setName('Nsds')
>>> bar.setName('Ysdy')
>>> foo.greet()
Hello,world! I'm Nsds
>>> bar.greet()
Hello,world! I'm Ysdy

When calling foo's setName and greet functions, foo automatically passes itself into the function as the first parameter, so it is named self. Without self, member methods cannot access the object itself on which they want to operate its properties.

Properties can be accessed externally:

>>> foo.name
'Nsds'
>>> bar.name='Yoda'
>>> bar.greet()
Hello,world! I'm Yoda

Features, functions, methods

The self parameter is actually the difference between methods and functions. Methods bind their first parameter to the corresponding instance, so this parameter does not need to be provided. So you can bind the properties to a normal function, so there will be no special self parameters:

(Characteristics are variables inside the object. The state of the object is described by its properties. The object's methods You can change its characteristics and access the characteristics directly from outside the object)

>>> class Class:
    def method(self):
        print 'I have a self!'

        
>>> def function():
    print "I don't..."

>>> s=Class()
>>> s.method()
I have a self!
>>> s.method=function
>>> s.method()
I don't...

The variable birdsong refers to the binding method bird.sing, or access to the self parameter (Still bound to the same instance of the class)

>>> class Bird:
    song='Squaawk'
    def sing(self):
        print self.song

        
>>> bird=Bird()
>>> bird.sing()
Squaawk
>>> birdsong=bird.sing
>>> birdsong()
Squaawk

A method or attribute can be made private (not accessible from the outside) by prefixing the name with a double underscore. Access)

>>> class Secretive:
    def __inaccessible(self):
        print "Bet you can't see me..."
    def accessible(self):
        print "The secret message is:"
        self.__inaccessible()

        
>>> s=Secretive()
>>> s.__inacessible()

Traceback (most recent call last):
  File "", line 1, in 
    s.__inacessible()
AttributeError: 'Secretive' object has no attribute '__inacessible'
>>> s.accessible()
The secret message is:
Bet you can't see me...

In the internal definition of a class, all names starting with a double underscore are "translated" into names preceded by a single underscore and the class name. Form

>>> Secretive._Secretive__inaccessible
>>> s._Secretive__inaccessible()
Bet you can't see me...

Namespace of class

When a class is defined, all code located in the class statement is executed in a special namespace - --The namespace of the class. This namespace is accessible to all members of the class.

The definition of the class is actually the execution code block

>>> class MemberCounter:
    members=0
    def init(self):
        MemberCounter.members+=1

        
>>> m1=MemberCounter()
>>> m1.init()
>>> m1.members
>>> m1.members=2
>>> m1.members
>>> m2=MemberCounter()
>>> m2.init()
>>> m2.members
>>> m2.init()
>>> m2.members
>>> m1.members
>>>

The new members value is written into the characteristics of m1. Masked variables within class scope

Superclass

>>> class Filter:
    def init(self):
        self.blocked=[]
    def filter(self,sequence):
        return [x for x in sequence if x not in self.blocked]

    
>>> class SPAMFilter(Filter):
    def init(self):
        self.blocked=['SPAM']

        
>>> f=Filter()
>>> f.init()
>>> f.filter([1,2,3])
[1, 2, 3]
>>> s=SPAMFilter()
>>> s.init()
>>> s.filter(['SPAM','SPAM','egg','name','ff'])
['egg', 'name', 'ff']

Inheritance, superclass

>>> class Filter:
    def init(self):
        self.blockes=[]
    def filter(self,sequence):
        return [x for x in sequence if x not in self.blocked]

    
>>> class S(Filter):
    def init(self):
        self.blocked=['s']

        
>>> f=Filter()
>>> f.init()
>>> f.filter([1,2,3])

Multiple super classes

Methods in the class that is inherited first will override methods in the class that is inherited later

>>> class C():
    def calculate(self,expression):
        self.value=eval(expression)

        
>>> class Talker():
    def talk(self):
        print 'Hi,my value is',self.value

        
>>> class TalkingCalculator(C,Talker):
    pass

>>> tc=TalkingCalculator()
>>> tc.calculate('1+2*3')
>>> tc.talk()
Hi,my value is 7

For more articles related to detailed explanations of classes and types in python, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn