First form
#! /Usr/bin/env python
# Coding = UTF-8
Class Person (object): # object indicates that it is inherited from the object class and may be omitted in Python3.
"""
This is a sample of Class
"""
Breast = 90 # class attributes are static variables
Def _ init _ (self, name): # The initialization method self is the object instance itself.
Self. name = name
Def get_name (self): # class method
Return self. name
Def color (self, color ):
D = {}
D [self. name] = color;
Return d
If _ name _ = "_ main __":
Girl = Person ("songjia ")
Print girl. name
Girl. name = "liu"
Print girl. get_name ()
Print girl. color ("white ")
Girl. breast = 80 # modifying instance attributes
Print girl. breast
Print Person. breast # The class attributes will not change with the instance attributes
People. breast = 100
Print Person. breast
Print girl. breast
Second Form
>>> _ Metaclass _ = type
>>> Class CC:
... Pass
...
>>> Cc = CC ()
>>> Cc. _ class __
<Class '_ main _. Cc'>
>>> Type (cc)
<Class '_ main _. Cc'>
Instance
Girl = Person ("songjia ")
Class attributes
>>> Class A (object): # Python 3: class:
... X = 7 # attributes of the class
...
The following lists the meanings of several special attributes of a class:
C. _ name _: return the class name in the form of a string. Note that this is only a string and it is not a class object.
C. _ doc _: Display class documents
C. _ base _: all parent classes of class C. If the class is defined according to the above method, the object should be displayed, because all the above classes inherit it. After learning "inheritance", let's take a look at this attribute to enrich the content.
C. _ dict _: display all attributes of a class in a dictionary.
C. _ module _: module of the class
Instance attributes
>>> Class A (object): # Python 3: class:
... X = 7 # attributes of the class
...
>>> Foo = ()
>>> Foo. x # instance attributes
Class variables reference variable data
>>> Class B (object ):
... Y = [1, 2, 3]
>>> B. y # class attributes
[1, 2, 3]
>>> Bar = B ()
>>> Bar. y # instance attributes
[1, 2, 3]
>>> Bar. y. append (4)
>>> Bar. y
[1, 2, 3, 4]
>>> B. y
[1, 2, 3, 4]
>>> B. y. append ("aa ")
>>> B. y
[1, 2, 3, 4, 'A']
>>> Bar. y
[1, 2, 3, 4, 'A']
When a variable in a class references a mutable object, both class attributes and instance attributes can directly modify this object, thus affecting the value of the other party.
Access restrictions
#! /Usr/bin/env python
# Coding = UTF-8
Class Person (object ):
"""
This is a sample of Class
"""
Def _ init _ (self, name): # The initialization method self is the object instance itself.
Self. _ name = name #__ xx double underline indicates the private variable of the class
Def get_name (self): # class method
Return self. _ name # internal access of the class
If _ name _ = "_ main __":
Girl = Person ("songjia ")
Print girl. get_name ()
Print girl. _ name # Private variables of the failed class
Document string
Write the document string description at the beginning of a function, class, or file. Generally, the double quotation marks are used. The biggest advantage of this write is that it can be viewed using the help () function.
"This is python lesson """
Def start_func (arg ):
"This is a function ."""
Pass
Class MyClass:
"This is my class ."""
Def my_method (self, arg ):
"This is my method ."""
Pass
Inheritance
Single Inheritance
#! /Usr/bin/env python
# Coding = UTF-8
Class Person (object): # Python 3: class Person:
Def _ init _ (self, name ):
Self. name = name
Def height (self, m ):
H = dict (["height", m],)
Return h
Def breast (self, n ):
B = dict (["breast", n],)
Return B
Class Girl (Person): # inherit
Def get_name (self ):
Return self. name
If _ name _ = "_ main __":
Cang = Girl ("liuguoquan ")
Print cang. get_name () # Python 3: print (cang. get_name (), the same below, from
Print cang. height (160)
Print cang. breast (90)
Call override method
Class Girl (Person ):
Def _ init _ (self, name ):
# Person. _ init _ (self, name) # call the method of the parent class
Super (Girl, self). _ init _ (name) # common method for calling the parent class
Self. real_name = "Aoi sola"
Def get_name (self ):
Return self. name
If _ name _ = "_ main __":
Cang = Girl ("canglaoshi ")
Print cang. real_name
Print cang. get_name ()
Print cang. height (160)
Print cang. breast (90)
The execution result is:
Aoi sola
Canglaoshi
{'Height ': 160}
{'Breast ': 90}
Multi-inheritance
#! /Usr/bin/env python
# Coding = UTF-8
Class Person (object): # Python 3: class Person:
Def eye (self ):
Print "two eyes"
Def breast (self, n ):
Print "The breast is:", n
Class Girl (object): # Python 3: class Gril:
Age = 28
Def color (self ):
Print "The girl is white"
Class HotGirl (Person, Girl): # Multi-inheritance
Pass
If _ name _ = "_ main __":
Kong = HotGirl ()
Kong. eye ()
Kong. breast (90)
Kong. color ()
Print kong. age
Two eyes
The breast is: 90
The girl is white
28
Sequence of multiple inheritance-breadth first
Class K1 (object): # Python 3: class K1:
Def foo (self ):
Print "K1-foo" # Python 3: print ("K1-foo"), the same below, from
Class K2 (object): # Python 3: class K2:
Def foo (self ):
Print "K2-foo"
Def bar (self ):
Print "K2-bar"
Class J1 (K1, K2 ):
Pass
Class J2 (K1, K2 ):
Def bar (self ):
Print "J2-bar"
Class C (J1, J2 ):
Pass
If _ name _ = "_ main __":
Print C. _ mro __
M = C ()
M. foo ()
M. bar ()
K1-foo
J2-bar
Print C. _ mro _ in the code is to print the inheritance order of the class. We can see from the above clearly. If you want to execute the foo () method, first check J1. No, check J2. No, check K1 in J1, C => J1 => J2 => K1; bar () is also in this order, and A is found in J2.
This order of inheritance attributes and method search is called "breadth first ".
The new classes of Python 2 and Python 3 follow this sequence to search for attributes and methods.
Method
Binding method
#! /Usr/bin/env python
# Coding = UTF-8
Class Person (object): # Python 3: class Person:
Def eye (self ):
Print "two eyes"
Def breast (self, n ):
Print "The breast is:", n
Class Girl (object): # Python 3: class Gril:
Age = 28
Def color (self ):
Print "The girl is white"
Class HotGirl (Person, Girl): # Multi-inheritance
Pass
If _ name _ = "_ main __":
Kong = HotGirl () # instantiate the method and bind the instance
Kong. eye () # Call the binding method
Non-binding method
In a subclass, the parent class method is a non-binding method, because in the subclass, the parent class instance is not created, but the parent class method is used.
Static methods and class methods
#! /Usr/bin/env python
# Coding = UTF-8
_ Metaclass _ = type
Class StaticMethod: # static method
@ Staticmethod
Def foo ():
Print "This is static method foo ()."
Class ClassMethod: # class method
@ Classmethod
Def bar (cls): # The Class method must have the cls parameter
Print "This is class method bar ()."
Print "bar () is part of class:", cls. _ name __
If _ name _ = "_ main __":
Static_foo = StaticMethod () # instantiate
Static_foo.foo () # Call the static method of the instance
StaticMethod. foo () # call static methods through classes
Print "********"
Class_bar = ClassMethod ()
Class_bar.bar ()
ClassMethod. bar ()
This is static method foo ().
This is static method foo ().
********
This is class method bar ().
Bar () is part of class: ClassMethod
This is class method bar ().
Bar () is part of class: ClassMethod
In python:
@ Staticmethod: The following method is a static method.
@ Classmethod: The following method is a class method.
Polymorphism and encapsulation
Polymorphism
Class Cat:
Def speak (self ):
Print "meow! "
Class Dog:
Def speak (self ):
Print "woof! "
Class Bob:
Def bow (self ):
Print "thank you, thank you! "
Def speak (self ):
Print "hello, welcome to the neighborhood! "
Def drive (self ):
Print "beep, beep! "
Def command (pet ):
Pet. speak ()
Pets = [Cat (), Dog (), Bob ()]
For pet in pets:
Command (pet)
Polymorphism in Python. Python does not check the type of the input object. This method is called "implicit type" (laten typing) or "Ural typing ), also known as "duck type" (duck typeing), Python is a weak type language.
Java checks the type of the input object, so it is a strongly typed language.
Encapsulation and privatization
To understand encapsulation, we can't do without "privatization", that is, to limit certain attributes of a class or function to a certain region and cannot be called externally.
The method of privatization in Python is also relatively simple, that is, the name of the property (including the method and data) to be privatized is prefixed with double underscores. For example:
#! /Usr/bin/env python
# Coding = UTF-8
Class ProtectMe (object): # Python 3: class ProtectMe:
Def _ init _ (self ):
Self. me = "qiwsir"
Self. _ name = "kivi" # Private variables
Def _ python (self): # Private method
Print "I love Python ."
Def code (self ):
Print "Which language do you like? "
Self. _ python ()
If _ name _ = "_ main __":
P = ProtectMe ()
Print p. me
Print p. code ()
How does one call a method into a property?
You can use the property function.
#! /Usr/bin/env python
# Coding = UTF-8
Class ProtectMe (object): # Python 3: class ProtectMe:
Def _ init _ (self ):
Self. me = "qiwsir"
Self. _ name = "kivi" # Private variables
Def _ python (self): # Private method
Print "I love Python ."
@ Property
Def code (self ):
Print "Which language do you like? "
Self. _ python
If _ name _ = "_ main __":
P = ProtectMe ()
Print p. me
Print p. code # call the method name