Classes and objects for Python

Source: Internet
Author: User

I. Object-oriented and process-oriented

1.1 Process-oriented features

The advantage is that it greatly reduces the complexity of the writing process, and only needs to stack the code along the steps to be performed.

The disadvantage is: a set of pipeline or process is to solve a problem, code reaching.

1.2 Process-oriented features

The advantage is that it solves the extensibility of the program. A single modification of an object is immediately reflected in the entire system, such as the character of a character parameter in the game and the ability to modify it easily.

Cons: Poor controllability, inability to process-oriented programming pipeline can be very accurate prediction of the problem of the processing process and results, the object-oriented program once the beginning of the interaction between the object to solve the problem

II. Classes and objects

Learn about nouns: classes, objects, instances, instantiation

Class: A category of things (people, dogs, tigers) with the same characteristics

2.1 Class and object definitions

Thus a class of things that have the same characteristics and skills are ' classes ', and the object is the specific one in this class of things.

Class Name:
def __init__ (self, parameter 1, parameter 2):
Self. Properties of the Object 1 = parameter 1
Self. Properties of the Object 2 = parameter 2

def method name (self):p

Def method Name 2 (self):p

Object name = Class name (#对象就是实例), which represents a specific thing
#类名 (): Class name + parenthesis is the instantiation of a class, equivalent to calling the __init__ method
#括号里传参数, the parameter does not need to pass self, and the other corresponds to the formal parameter one by one in Init
#结果返回一个对象
Object name. The object's property 1 #查看对象的属性, directly with the object name. Property name
The name of the object. Method Name () #调用类中的方法, directly with the object name. Method Name ()

Supplement to Class 2.2 properties

One: Where do the properties of the class we define are stored? There are two ways to view the
Dir (class name): A list of names is found
class name. __dict__: A dictionary is found, key is the property name, value is the property value

Two: Special class attribute
Class name. __name__# Class Name ( String) the
class name. The document string
class name of the __doc__# class. The first parent class of the __base__# class (Speaking of inheritance)
class name. A tuple of all the parent classes of the __bases__# class (Speaking of inheritance)
class name. __dict__# The dictionary property of the class
class name. The module
class name where the __module__# class is defined. Class for __class__# instances (in modern class only)

Lass Person:  # defines a human     'man'  # People's role attributes are all human    def __init__ ( Self, name, aggressivity, life_value):        = name  # Each character has its own nickname;         = aggressivity  # Each character has its own attack;         = Life_value  # Each character has its own health value;    Def attack (Self,dog):          # People can attack a dog, and the dog here is also an object.        # People attack the dog, then the dog's health will fall        according to the attack . -= Self.aggressivity

Object/instance has only one function: Property reference

Egg = person (' Egon ', 10,1000)
Print (Egg.name)
Print (egg.aggressivity)
Print (Egg.life_value)

2.3 Interaction between objects

classpersion:def __init__ (self,name,hp,dps,sex): Self.name=name SELF.HP=HP Self.dps=DPS Self.sex=Sex def attack (Self,dog): dog.hp-=Self.dps Print ('%s bit the%s,%s dropped the%s point of blood, the remaining%s blood'%(Self.name, Dog.name, Dog.name, Self.dps, dog.hp))classdog:def __init__ (Self,name,kind,hp,dps): Self.name=name SELF.HP=HP Self.dps=DPS Self.kind=kind def bit (self,persion): persion.hp-=Self.dps Print ('%s bit the%s,%s dropped the%s point of blood, the remaining%s blood'%(Self.name,persion.name, Persion.name, Self.dps, PERSION.HP)) Alex=persion ('Alex', -,5,'N /A') HA2=dog ('Husky','Tibetan Mastiff',15000, $) Print (Alex.attack (HA2)) print (Ha2.bit (Alex) )
examples of man and dog wars

Namespaces for class namespaces and objects, instances

Creating a class creates a namespace for a class that stores all the names defined in the class, called Properties of the class

The class has two properties: static property and dynamic property

A static property is a variable that is defined directly in the class

A dynamic property is a method defined in a class

Where the data properties of a class are shared to all objects

>>>ID (egg.role)4341594072>>>id (person.role

The dynamic properties of a class are bound to all objects.

>>>egg.attackobject0x101285860>>>>>person.attack 0x10127abf8
View Code

Four, object-oriented combination usage

The important way of software reuse in addition to inheritance there is another way, namely: the combination

A combination refers to a class in which an object of another class is used as a data property, called a combination of classes

 class   Weapon:def prick (self, obj): # This is the device's active skill, killing each other obj.life_value -= 500   # Assumptions Attack is a  class   person: # define a human role  =  " person   "  # Man's role attributes are Human def __init__ (self, name): Self.name  = name # each character has its own nickname;        Self.weapon  = weapon () # binds a weapon to the character; Egg  = person ( " egon  "  ) Egg.weapon.prick () #egg组合了一个武器的对象, You can egg.weapon directly to use all the methods in a composition class  
attach a weapon to the character

The ring is made up of two circles, and the area of the ring is the area of the outer circle minus the inner circle. The perimeter of the ring is the perimeter of the inner circle plus the perimeter of the outer circle.
At this point, we will first implement a circular class that calculates the circumference and area of a circle. And then, in the ring class, an instance of the combined circle is used as its own property.

 fromMath Import PiclassCircle:" "defines a circular class; Provides methods for calculating area and perimeter (perimeter)" "def __init__ (Self,radius): Self.radius=radius def area (self):returnPI * Self.radius *Self.radius def perimeter (self):return 2* PI *self.radiuscircle= Circle (Ten) #实例化一个圆area1=Circle.area () #计算圆面积per1=Circle.perimeter () #计算圆周长print (area1,per1) #打印圆面积和周长classRing:" "defines a method by which a ring class provides the area and perimeter of a ring" "def __init__ (self,radius_outside,radius_inside): Self.outsid_circle=Circle (radius_outside) self.inside_circle=Circle (radius_inside) def area (self):returnSelf.outsid_circle.area ()-Self.inside_circle.area () def perimeter (self):returnSelf.outsid_circle.perimeter () +Self.inside_circle.perimeter () ring= Ring (Ten,5) #实例化一个环形print (Ring.perimeter ()) #计算环形的周长print (Ring.area ()) #计算环形的面积
View Code

Five, object-oriented three major characteristics (inheritance, encapsulation, polymorphism)

5.1 Inheritance

The concept of 5.1.1 inheritance

Inheritance is a way of creating new classes in Python, where a new class can inherit one or more parent classes, which can be called a base class or a superclass, and a new class is called a derived class or subclass.

The inheritance of classes in Python is divided into: single inheritance and multiple inheritance

Definition of 5.2.2 Inheritance

class ParentClass1: #定义父类    passclass  ParentClass2: #定义父类    passclass  SubClass1 (PARENTCLASS1): #单继承, the base class is ParentClass1, and the derived class is subclass    Passclass  SubClass2 ( PARENTCLASS1,PARENTCLASS2): #python支持多继承, separate multiple inherited class    pass with commas
View Code

5.2.3 Viewing inheritance

>>> subclass1.__bases__ #__base__只查看从左到右继承的第一个子类, __bases__ is looking at all inherited parent classes
(<class ' __main__. ParentClass1 ';,)
>>> subclass2.__bases__
(<class ' __main__. ParentClass1 ';, <class ' __main__. ParentClass2 ' >)

5.1.4 Inheritance and abstraction (first abstraction and inheritance)

Abstraction is the extraction of a similar or more like part.

An abstraction is divided into two levels:

1. Take the parts of Barack Obama and Lionel Messi, which are more like the two, into categories;

2. Extract the three categories of people, pigs, and dogs into a parent class.

The main function of abstraction is to classify categories (which can isolate concerns and reduce complexity).

Inheritance: is based on abstract results, through the programming language to achieve it, it must be through the process of abstraction, in order to express the abstract structure through inheritance.

Abstraction is just the process of analysis and design, an action or a skill that can be obtained by abstracting the class

5.1.5 derivation

Of course, subclasses can also add their own new properties or redefine them here (without affecting the parent class), and it is important to note that once you have redefined your own properties and have the same name as the parent, you will be able to invoke the new attributes when you call them.

classAnimal:" "Both humans and dogs are animals, so create a animal base class" "def __init__ (self, name, aggressivity, life_value): Self.name=name # Man and dog have their nicknames; Self.aggressivity=aggressivity # People and dogs have their own attack; Self.life_value=Life_value # People and dogs have their own health values; Def eat (self): print ('%s is eating'%self.name)classDog (Animal):" "Dog class, inheriting animal class" "def bite (Self, people):" "derived from: The dog has the skill of biting people:p Aram people:" "People.life_value-=self.aggressivityclassPerson (Animal):" "man, inherit animal." "def attack (self, dog):" "derivation: Man has the skill to attack:p Aram Dog:" "Dog.life_value-=Self.aggressivityegg= Person ('Egon',Ten, +) HA2= Dog ('Erlengzi', -, +) print (ha2.life_value) print (Egg.attack (HA2)) print (Ha2.life_value)
View Code

5.4 Diamond Inheritance

Inheritance Order

classAObject): def Test (self): print ('From A')classB (A): Def Test (self): print ('From B')classC (A): Def Test (self): print ('From C')classD (B): Def Test (self): print ('From D')classE (C): Def Test (self): print ('From E')classF (d,e): # def Test (self): # print ('From F') Passf1=f () F1.test () print (f.__mro__) #只有新式才有这个属性可以查看线性列表, the classic class does not have this property # new class inheritance order: F->d->b->e->c->a# Classic class inheritance order: F->d->b->a->e->The unification of C#python3 is the new class and the classic class in the new type #pyhon2 want $
Inheritance Order

Summary:

The role of inheritance

Reduce code reuse to improve code readability specification programming patterns

Inheritance noun explanation

Abstraction: Abstraction is the extraction of a similar or more like part. is a process from a problem to an abstraction. Inheritance: Subclasses inherit methods and property derivations of the parent class: Subclasses produce new methods and properties based on parent class methods and properties

Diamond Inheritance

New class: Breadth First Classic class: depth first

Classes and objects for Python

Related Article

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.