The third chapter of Python-Object oriented

Source: Internet
Author: User

Classes and objects

Classes and objects in Pyhon are very different from classes and objects in C + +, but they are all designed to encapsulate the properties and methods of an object, and the methods used for Pyhon classes and objects are discussed in detail below.

one, the constructor  
class Foo:     def __init__ (num):         = num
F=foo (1)

The __init__ () method is called automatically when the object is initialized with a class.

Second, class properties and instance properties

Class properties can be invoked through an instance object or the class itself.

class Foo:     " Isfoo "    def __init__ (self):         Pass  Fooprint#isfooprint(foo.name)# Isfoo

Instance properties can be bound by constructors, or they can be directly bound

class Foo:     def __init__ (self,name):          = Foo ("Jack"= 18
Print (F.name) #Jack# Instance properties can be viewed through the property dictionary for print(f.__dict__) # {' name ': ' Jack ', ' age ':

Precautions:

1, class properties can only be modified by class invocation

2, if the Class property is modified with the instance area, an instance property with the same name as the Class property will be set directly

Third, inherit

Python3 are all new classes, that is, the class inherits it by default, regardless of whether it inherits the object class.

 class   Animal:  def   Eat (self):  print  ( Span style= "COLOR: #800000" > " %s eating sth   "% Self.name)  class   Cat (Animal):  def  __init__   = Namec  = Ca T ( " miaomiao   " ) c.eat ()  #   m Iaomaio eating sth  

If a subclass has no constructors, the constructor of the parent class is used, and if so, there are two ways to invoke the constructor of the parent class

classAnimal:def __init__(self,age): Self.age= AgedefEat (self):Print("%s eating sth"%self.name)classCat (Animal):def __init__(self, name,age):#animal.__init__ (self,age) #firstSuper ().__init__(age)#SecondSelf.name = Name

  Abstract class

Four, combination and reuse

When several classes have common attributes, we can abstract the common part as the parent class, and the combination is a kind of all relationships, such as school and teacher, class and student.

classStudent:def __init__(self,name,age): Self.name=name Self.age= AgeclassClass_grade:def __init__(self): Self.li=[]    defput (self,name,age): Self.li.append (Student (name, age)) C=Class_grade () c.put ("Jack", 18)Print(C.li[0].name,c.li[0].age)#Jack

Five, Package

The package has two features:

Encapsulates properties and methods in an object, hides details, and provides only interfaces;

have access control;

The first feature has been explained in the previous article, so let's look at the access control in the Python class.

In Python, there is no real restriction on the external or subclass of the class's access to the data inside the class, but rather a convention that hides it without direct exposure.

  Hide by double underline

classFoo:__n=2def __init__(self): self.__name="Jack"    deffunc (self):Print(self.)__n)#0        Print(self.)__name)#the inside of the Jack class can be accessed directly by namef=Foo () f.func ()#print (self.__name) name # ' self ' was not defined#print (f.__n) # ' Foo ' object has no attribute ' __n 'Print(F._foo__n)#instance properties and function properties can be accessed through the _ Class name __ variable name similarly    

The problems to be aware of in this deformation are:

1. This mechanism also does not really restrict our direct access to properties from the outside, know the class name and property name can be spelled out name: _ Class Name __ property, then you can access, such as A._a__n, that this is not strictly restricting external access,

is only a syntactic distortion, mainly used to restrict external direct access.

2. The process of deformation occurs only once when the class is defined, and the assignment operation after the definition does not deform

Then we can use the following method to provide an external method for the outside of the class to face the private variable- friendly access

Property (attribute)

classFoo:__n= 2def __init__(self): self.__name="Jack"@property #访问defname (self):returnSelf.__name@name. Setter #设置值defname (self, value):if  notisinstance (value, str):Print("Please enter a string type")        Else: Self.__name=value @name. deleter #删除defname (self):delSelf.__nameF= Foo ()
Print(F.name)#像是调用属性, actually invoking the method, also conforms to the actual
F.name= "Bob"
Del F.name

  Different access controls can be implemented by implementing different functions

Six, polymorphic

Let's review the polymorphism in C + +: When a parent pointer (reference) refers to a subclass or parent object, different methods are invoked based on the type of the actual object. In Python, because they are dynamic data types, the assignment is initialized, so polymorphism tends to be more of a code logic than a syntax.

classDemo1:defdisplay (self):Print("this is Demo1 .")classDemo2:defdisplay (self):Print("this is Demo2 .")classDemo3:defdisplay (self):Print("this is Demo3 .")deffunc (obj): Obj.display ()if __name__=='__main__': D1=demo1 () D2=Demo2 () D3=Demo3 ()#---Call different manifestations of the same function--Func (D1)#this is Demo1 .Func (D2)#this is Demo2 .Func (D3)#this is Demo3 .

The third chapter of Python-Object oriented

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.