Python object-oriented Supplement

Source: Internet
Author: User

How to use Classes

I. Instantiation: creating an Object

Example One

X=int () Print (x)

Everything in Python is an object, and Python3 unifies the concept of classes and types, which are classes

>>> dict #类型dict就是类dict <class ' dict ' >>>> d=dict (name= ' Egon ') #实例化 >>> d.pop (' name ') # Sends a message to d, executes the method pop of D. ' Egon '

  

Example Two:

Class garen:    camp= ' Demacia '    def attack (self):        print (' attack ') Obj=garen ()    #实例化, Instance is object print (obj) #- ---> <__main__. Garen Object at 0x0000000001e7cc18>

Ii. characteristics of a reference class (variables of a class) and skills (functions of a Class) 

Based on object-oriented design a game: League of legends, each player choose a hero, each hero has his own characteristics and skills,

Feature is the data attribute, the skill is the method attribute, the characteristic and the Skill's union body is an object.

Extracting similar parts from a set of objects is a combination of features and skills that all objects in a class have

In python, a variable represents a feature, a function represents a skill, and a class is a combination of a variable and a function, and an object is a combination of a variable and a method (a function that points to a class).

Class garen:    camp= ' Demacia '    #变量代表特征    def attack (self): print (        ' attack ') #函数代表技能 print ( Garen.camp)---->demaciaprint (garen.attack)---> <function Garen.attack at 0x0000000001e7f158> Garen.attack (123)---->attack

  

How to use an instance

Class garen:    camp= ' Demacia '    #变量, common features    def __init__ (self,nickname):        self.nick=nickname   # variable, unique feature    def attack (self,enemy):        #函数, Skill        # print ('----> ', self.nick) #g1. Nick        print ('%s attack%s '% (self.nick,enemy)) g1=garen (' Bush lun ') #Garen. __init___ (g1, ' Bush lun ') g2=garen (' wretched wheel ') print (g1.nick)----> Bush Roentgen G1.attack (' Alex ')----> Bush attack Alexprint (g1.camp)---->demaciaprint (g1.attack)---> <bound method Garen.attack of <__main__. Garen object at 0x00000000027bcd30>>print (garen.attack)----><function Garen.attack at 0x00000000021DF048 >  

Class student:country= ' China ' def __init__ (self,id,name,sex,province): Self.id=id self.name=name        Self.sex=sex self.province=province def search_score (self): print ("tell Score") def study (self): Print (' study ', self) s1=student (' 123 ', ' Egon ', ' male ', ' shandong ') print (student.__init__ (s1, ' 123 ', ' Egon ', ' male ', '           Shandong ') #调用__init__函数----> none# to invoke the Object's properties: the object itself is only a feature (variable) s1.id= ' 123 ' #调用对象的id属性s1. name= ' Egon ' #调用对象的name属性s1. sex= ' male ' #调用对象的sex属性s1. province= ' Shandong ' #调用对象的province属性 # view function Print (student.countr Y) #查看类的数据属性---->chinaprint (student.__init__)----><function student.__init__ at 0x0000000001e73b70>p Rint (student.study)----><function student.study at 0x0000000001e7f2f0>print (student.search_score)---- ; <function Student.search_score at 0x000000000221f2f0>student.__init__ (s1, ' 123 ', ' Egon ', ' male ', ' Shandong ') Student.study (s1)---->study <__main__. Student Object at 0x00000000021ec470>

Summarize:

Class: one: instantiation, second: reference name (class name. name of the variable, class Name. function Name)
Instance: reference name (instance name, variable of class, instance name.) bind method, instance name. instance's own variable Name)

Addition and subtraction of variables and their calculation
#变量的增删改查class garen:    camp= ' Demacia '    def __init__ (self,nickname):        self.nick=nickname  #g1. nick= ' Bush Roentgen '    def attack (self,enemy):        print ('%s attack%s '% (self.nick,enemy)) print (garen.camp) #查----> demaciagaren.camp= ' aaaaaa ' #改print (garen.camp)---->aaaaaadel garen.camp #删除print (garen.camp) #报错:----> Attributeerror:type object ' Garen ' has no attribute ' camp ' garen.x=1 #增print (garen.x)---->1g1=garen (' Alex ') Print ( g1.nick)---->alexg1.nick= ' ASB ' #改print (g1.nick)---->asbdel g1.nick   #删print (g1.nick) #报错:----> Attributeerror: ' Garen ' object has no attribute ' Nick ' g1.sex= ' female '   #增print (g1.sex)---->femalegaren.x= 1garen.y=2garen.res=garen.x+garen.yprint (garen.res=garen.x+garen.y)---->3

All the classes in Python3 are new classes

Class A:passprint (a.__bases__)   #__bases__查看继承----> (<class ' Object '), inherited is a new class of object

The Python2 is divided into the new class and the classic class

The biggest difference between a new class and a classic class declaration is that all modern classes must inherit at least one parent class

All classes do not explicitly declare a parent class, there is a default inheritance object parent class

Python2 class B (object):p assclass C (b):p assprint (b.__bases__)  #__bases__查看继承----> (<class ' object ' ,) print (c.__bases__)----> (<class ' __main__. B ';,)

#python2中经典类class D:passprint (d.__bases__)----> ()

In python3, the new class and the classic class are all Modern.

The namespace of the class and the namespace of the object

Class student:country = ' China ' def __init__ (self, id, NAME, SEX, province): self.id = ID Self.name = NAME self.sex = Sex self.province = Province def search_score (self): print (' tell score ') def s Tudy: #self =s1 Print (' study ', self) def walk (self): print (' name:%s is walking '%self.name) S1 = stude NT (' 123 ', ' Cobila ', ' female ', ' shanxi ') s2 = Student (' 124 ', ' Cobilamei ', ' femaleasfd ', ' Shasdfanxi ') s1.walk ()----> Name:cobila is Walkings2.walk ()---->name:cobilamei is walkingprint (student.__dict__) #__dict__, look at the namespace, view the namespace of the class-- -->{' __module__ ': ' __main__ ', ' country ': ' China ', ' __init__ ': <function student.__init__ at 0x00000000021d3a60 , ' Search_score ': <function student.search_score at 0x00000000021df048>, ' study ': <function Student.study At 0x00000000021df2f0>, ' Walk ': <function student.walk at 0x00000000021df158>, ' __dict__ ': <attribute ' __ dict__ ' of ' Student ' objects>, ' __weakref__ ': &Lt;attribute ' __weakref__ ' of ' Student ' objects>, ' __doc__ ': None} print (s1.__dict__) #__dict__, view namespace, View Object's namespace {' ID ': ' 123 ', ' name ': ' Cobila ', ' sex ': ' female ', ' province ': ' Shanxi '} print (s1.id)---->123 s1.country= "321" print (id (s 1.country)---->42061192 print (s2.id)---->124 s2.country= "421" print (id (s2.country))---->42061248# binding method, The core of the binding method is "binding", uniquely binding a certain object print (s1.study,id (s1.study))----><bound method Student.study of <__main__. Student object at 0x000000000284ceb8>> 5139208print (student.study,id (student.study))----><function Student.study at 0x000000000284f2f0> 42267376

Interaction between objects

Class Riven:    camp= ' Noxus '  #所有玩家的英雄 (rui Wen) 's camp are all noxus;    def __init__ (self,nickname,aggressivity=54,life_value=414): #英雄的初始攻击力54;        Self.nickname=nickname  #为自己的锐雯起个别名;        Self.aggressivity=aggressivity #英雄都有自己的攻击力;        Self.life_value=life_value #英雄都有自己的生命值;    def attack (self,enemy):   #普通攻击技能, Enemy is the enemy;        Enemy.life_value-=self.aggressivity #根据自己的攻击力, attack the enemy and lose the Enemy's Health. Class garen:    camp= ' Noxus '  #所有玩家的英雄 (rui Wen) 's camp are all noxus;    def __init__ (self,nickname,aggressivity=54,life_value=414): #英雄的初始攻击力54;        Self.nickname=nickname  #为自己的锐雯起个别名;        Self.aggressivity=aggressivity #英雄都有自己的攻击力;        Self.life_value=life_value #英雄都有自己的生命值;    def attack (self,enemy):   #普通攻击技能, Enemy is the enemy;        Enemy.life_value-=self.aggressivity #根据自己的攻击力, attack the enemy and lose the Enemy's Health. # Interaction between Objects R1=riven (' Ru Wenwen ') g1=garen (' grass wheel ') print (r1.life_value)---->414g1.attack (r1) print (r1.life_value)----> 360name=input (' your nickname: ') r1=riven (name)

 

Object-oriented Programming Thinking

#应用场景 # Can't find common features and skills no need to force # object: school-----> Classification    #共有的特征: trademark for Etiantian    #共有的技能: admissions    #独有的特征: Address different, teachers, Course class School :    tag= ' Etiantian '    def __init__ (self,addr):        self.addr=addr        self.teacher_list=[]        self.course_ list=[]    def Zhaosheng (self):        pass# object: teacher----> classification    #共同的技能: teach    #独有的特征: name, gender, level, class Teacher:    def __init__ (self,name,sex,level):        self.name=name        self.sex=sex        self.level=level        self.course_list=[]            def teach (self):        pass# object: student----> classification    #共同的特征:    #共同的技能: search_score , Handin    #独有的特征: School number, name, gender, Course class Student:    def __init__ (self,id,name,sex):        self.id=id        Self.name=name        self.sex=sex        self.course_list=[]    def search_score (self):        pass    def Handin (self):        Pass

  

Python object-oriented Supplement

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.