Python 11 Classes and objects

Source: Internet
Author: User

To introduce you to the object hhhh

Packaging

For example, the messy data is still on the list, and the data-level encapsulation

Package common code into a function that encapsulates

What the appearance characteristics (static) can do (dynamic)

Object = Property (Static) + method (dynamic)

1. Methods Multi-purpose functions

2. Class is a drawing, object is made according to the drawing of things

3. Classes are like functions in the overall structure, so in order to differentiate, the first letter of the class is capitalized, the function is lowercase

Class Turtle: #封装类

Property

Method

def climb () #方法中的一个例子

Tt=turtle () #创建类, similar to a function

TT.CLIMD () #调用类中的函数

    

Oo Object-oriented

Encapsulation, Information masking technology list1.sort (), sorted list, no known process

inheritance, the mechanism by which subclasses automatically share data and methods between parent classes

Class Mylist (list): #继承list的方法和属性

Pass #什么都不用做

List2 = Mylist ()

List2.append (0)

List2

[0]

Polymorphic: Calling the same method on different objects, resulting in object changes

Class A:

def fun (self):

Print (' a ')

Class B:

def fun (self):

Print (' B ')

A=a ()

B=b ()

A.fun #a

B.fun #b

Object-Oriented Programming

Self to write into the first parameter object

Self name is not required, in Python self is not a keyword, you can define a or B or other names can be, but the contract idiomatic (in order to unify with other programming languages, reduce the difficulty of understanding), do not engage in alternative, we will not understand.

Self refers to the class instance object itself (address) (Note: Not the class itself).

function calls in class

After giving an instance, when we call a specific method (that is, a function) in the class, the self parameter is passed in by default (that is, the instance address)

Such objects are not unique and will run their own results.

Class Ba:

def setname (self,name): #self为实例地址

Self.name = name # substituting instance. Name = Name

def kick (self):

Print ('%s '% self.name) #打印 instance. Name

A = Ba ()

A.setname (' a ') #self地址为a (instance address)

b = Ba ()

B.setname (' B ')

c = Ba ()

C.setname (' 0 ')

A.kick () #a

C.kick () #0

constructor function

The constructor method is similar to the init () initialization method, which initializes the state of the newly created object and calls it immediately after an object class is created.

__init__ (Self,param1,param2 ...)

Class Ba:

def __init__ (Self,name)

Self.name = Name

def kick (self):

Print ('%s '% self.name)

b = Ba (' B ')

B.kick () #b

Class Per:

Name= ' a '

>>p = Per ()

>>p.name #a

Class Per:

__name= ' a '

def g (self):

Return Self.__name

>>p = Per ()

>>p.name #报错, __ for private

>>P.G #返回a

>>p._per__name #返回a

_ Class name __ variable name

Inherited

Class Deribedclassname (Baseclassname): # () in the parent class, name

Class Pae:

def hello (self):

Print (' Call parent class ')

Class Chi (Pae):

Pass

>>p = Pae ()

>>p.hello

Calling the parent class

>>c = Hello ()

>>c.hello ()

Calling the parent class

If a method or property with the same name as the parent class is defined in the child class, the corresponding method or property of the parent class is automatically overwritten

Not affected by parent class

Class Chi (Per):

def hello (self):

Print ("Call subclass")

>>c = Chi ()

>>c.hello ()

Calling subclasses

>>p.hello ()

Calling the parent class

ImportRandom as RclassFish:def __init__(self): self.x= R.randint (0,10) Self.y= R.randint (0,10)     defMove (self): self.x-= 1Print("My location:", SELF.X,SELF.Y)classGold (Fish):PassclassCarp (Fish):PassclassSa (Fish):PassclassShark (Fish):def __init__(self): #与父类冲突, overriding the parent class, requires a solution self.hungry=TruedefEat (self):ifself.hungry:Print("There's food every day.") Self.hungry=FalseElse:               Print("it's too much.")               

1. Calling an unbound parent class method

def __init__ (Fish):

Fish.__init__ (self) #在子类执行的前面调用父类, self is a subclass, Shark

Self.hugry = True

2. Using the Super function

def __init__ (Fish): #这里的父类是Fish, Super calls the __init__ () of the parent class

Super (). __init__ () #有很多父类也不用一个个写, automatic layer to find the __init__ () method,

Self.hugry = True

Multiple inheritance, write more than a few parents, try to avoid the use, there may be unforeseen bugs (fatal)

Composition: An object of another class in one class as a data property, called a combination of classes

Instance. Incoming class. Data in Class
classTurtle:def __init__(self,x): Self.num=xclassFISHL:def __init__(self,x): Self.num=xclassPool:def __init(self,x,y): Self.turtle=Turtle (x) #把T中数据调入self. Turtle, Self.turtle.num self.fish can be used=Fish (y) #实例. Transfer into class. Data in ClassdefPrint_num (self):Print("turtle%d, small fish%d"% (Self.turtle.num,self.fish.num))

Mix-in

Reproduced

classWeapon:defPrick (self, obj):#This is the device's active skill to kill each other .Obj.life_value-= 500#Assuming that the attack isclassPerson:#Define a humanRole =' Person'  #People's role attributes are people    def __init__(self, name): Self.name= Name#each character has its own nickname;Self.weapon = Weapon ()#bind a weapon to a character;Egg= Person ('Egon') Egg.weapon.prick ()#Egg combines the object of a weapon and can be egg.weapon directly to use all the methods in the composition class

The relationship between classes and classes is established in a combinatorial way, which is a ' have ' relationship, such as a professor having a birthday, teaching a python course

Man Dog War (reprint)

classPerson:#Define a humanRole =' Person'  #People's role attributes are people    def __init__(self, name, aggressivity, Life_value, Money): Self.name= Name#each character has its own nickname;Self.aggressivity = aggressivity#each character has its own attack power;Self.life_value = Life_value#each character has its own health value;Self.money = MoneydefAttack (Self,dog):#A man 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 .Dog.life_value-= self.aggressivity
classDog:#define a dog classRole ='Dog'  #the dog's character is all dogs.    def __init__(self, name, breed, aggressivity, life_value): Self.name= Name#every dog has its own nickname;Self.breed = Breed#every dog has its own breed;Self.aggressivity = aggressivity#every dog has its own attack;Self.life_value = Life_value#each dog has its own health value;    defBite (self,people):#a dog can bite, and the dog here is also an object.         #If the dog bites, the human health will fall according to the dog's attack.People.life_value-= self.aggressivity
classWeapon:#Equip    def __init__(Self,name, Price, Aggrev, Life_value): Self.name=name Self.price=Price Self.aggrev=Aggrev Self.life_value=Life_valuedefUpdate (self, obj):#obj was the one who was going to bring this outfit.Obj.money-= Self.price#people who use this weapon pay for it, so the money is reduced.Obj.aggressivity + = Self.aggrev#with this outfit, you can increase your attack.Obj.life_value + = Self.life_value#with this outfit, you can increase your health.    defPrick (self, obj):#This is the device's active skill to kill each other .Obj.life_value-= 500#Assuming that the attack is
Lance = Weapon ('Spear', 200,6,100) Egg= Person ('Egon', 10,1000,600)#created a real man, egg .HA2 = Dog ('Erlengzi','Husky', 10,1000)#created a real dog, HA2 .#Egg alone Ours "Erlengzi" deeply labored, decided to poor life savings to buy a weaponifEgg.money > Lance.price:#if egg is more expensive than equipment, buy a spear .Lance.update (egg)#Egg bought a spear for self-defense, and its properties were improved.Egg.weapon = Lance#the egg was equipped with a spear.Print(egg.money,egg.life_value,egg.aggressivity)Print(Ha2.life_value) egg.attack (HA2)#Egg hit HA2.Print(Ha2.life_value) Egg.weapon.prick (HA2)#Launch Weapon SkillsPrint(Ha2.life_value)#HA2 to a cunning man with a weapon to win, half the blood trough.

Reproduced

classBirthDate:def __init__(self,year,month,day): Self.year=Year Self.month=month Self.day= Dayclasscouse:def __init__(self,name,price,period): Self.name=name Self.price=Price Self.period=periodclassTeacher:def __init__(self,name,gender,birth,course): Self.name=name Self.gender=Gender Self.birth=Birth Self.course=CoursedefTeach (self):Print('Teaching') P1=teacher ('Egon','male', BirthDate ('1995','1',' -'), #把B中数据调入T中, instance P1
Couse ('python','28000','4 months') ) Print(P1.birth.year,p1.birth.month,p1.birth.day)Print(P1.course.name,p1.course.price,p1.course.period)" "running Result: 1995 1 python 28000 4 months" "

Class is the class object, the instance object

Class C:

def x:

Count = 0

>>a=c ()

>>b=c ()

>>c.count+=10 #创建实例对象的属性

>>c.x () #报错, property override method if same as method name

>>a.count

0

>>c.count

10

>>c.count #类对象

0

>>c.count + = 100

>>a.count #增加100

100

>>c.count #实例对象的属性, no change

10

Avoid this kind of thing, do not try to define all the features and methods that can be thought of in a class, and should be extended by reason inheritance and composition mechanism.

To name a different part of speech, such as a noun in a property name and a verb in a method name

About bindings

Class C:

def set (self,x,y)

self.x = X

Self.y = y

def printxy (self):

Print (SELF.X,SELF.Y)

>>d = C ()

>>d.__dict__

{}

>>c.__dice__

{............. Data, methods.}

>>d.set (#静态的绑定类对象的方法里)

>>d.__dice__

{' Y ': 2, ' X ': 1}

>>def C

>>e =c () #报错

>>d.printxy () #1 2

Use instance properties as much as possible, self

Do not use class properties

Python 11 Classes and objects

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.