程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python -- classes and objects, magic methods (day07)

編輯:Python

Catalog

One 、 object-oriented

Two 、 Classes and objects

3、 ... and 、 Instance methods and properties

Four 、__init__ Method

5、 ... and 、self

6、 ... and 、 Magic methods

7、 ... and 、 Duel

8、 ... and 、 Homework

Nine 、 Add

object-oriented programming :oop [object oriented programming] It's a kind of python Programming ideas
Process oriented : That's what we started learning , Follow the problem solving steps to write code 【 Write code according to business logic 】
When thinking about problems , First analysis ' How to follow the steps to achieve ' Then the problem solving is broken down into several steps , And these steps are corresponding to the step-by-step of the method Finally complete the function
object-oriented : Focus on design thinking 【 Find a car wash   Pay for the car wash 】

On a business trip -- Beijing
Xiao Ming -- What time? - - What ticket to buy 【 high-speed rail automobile The plane 】--- The hotel --- Return time
Do it yourself 【 Process oriented 】

Lack of process orientation : Xiao Ming doesn't have more energy to think about other things

boss--- secretary 【 What Xiao Ming needs to consider 】---- financial ---- Purpose : Beijing 【 object-oriented 】

boss Have more energy to deal with other times , Create more value

From a computer point of view : Process oriented is not suitable for large projects

Object oriented design is suitable for larger projects

Classes and objects

class : A class has a set of Having the same or similar characteristics 【 attribute 】 And behavior 【 Method 】 A series of [ Multiple ] Object combination

Real world     Computer world
Behavior ---------> Method
features ----------> attribute

object : The object is a real thing , Class instantiation , Concretion

A class is an abstraction of an object   An object is an instance of a class

Example method : Inside the class , Use def Keyword to define   The first parameter defaults to self【 The name identifier can be another name , But this position must be occupied 】

The example method is attributed to All instances of class

attribute : Class properties   Instance attributes
Variables defined inside the class 【 Class properties 】
Defined inside the method 【 Through similar self. Variable name 】 Variable , Is the instance property

One 、 object-oriented

The process oriented focus is : How do you do it?

Object oriented concerns are : Who will do it

Two 、 Classes and objects

 

 

3、 ... and 、 Instance methods and properties

self Just a keyword , You can change it to something else , It must exist in the class as the first parameter , It's just Example method , The instance method belongs to the instance , Any instance can call , An object is an instance of a class

# Define classes and objects
# Class structure Class name attribute Method
# class Class name :
# attribute
# Method
class Person:
'''
The characteristics of the corresponding person
'''
# name=' Xiao Ming ' # Class properties
age=20 # Class properties
'''
Corresponding person's behavior Example method
'''
def __init__(self):
self.name=' Xiao Ming ' # Instance attributes
pass
def eat(parms):
print(" A big meal ")
pass
def run(self): # Example method
print(' Run fast ')
pass
pass
def printInfo():
'''
Common method
:return:
'''
pass
# Create an object 【 Class instantiation 】
# Regular format Object name = Class name ()
xm=Person()
xm.eat() # Call function
xm.run()
print("{} The age of :{}".format(xm.name,xm.age))
# Create another instance object
xw=Person()
xw.eat() # Example method 

Four 、__init__ Method

 

  Class attribute methods cannot modify values , Instance properties can

__init__ Also called Initialization method

# class Pepole:
# def __init__(self):
# '''
# Declaration of instance properties
# '''
# self.name=' Small qian '
# self.sex=' girl student '
# self.age=20
# pass
# def eat(self):
# '''
# The act of eating
# :return:
# '''
# print(' Like to eat durian ')
# pass
#
# xq=Pepole()
# xq.name=' Small qian ' # Add instance properties
# xq.sex=' girl student ' # Add instance properties
# xq.age=20 # Add instance properties
# xq.eat()
# # print(xq.name,xq.sex,xq.age)
#
# xl=Pepole() # created
# xl.name=' Small qian ' # Add instance properties
# xl.sex=' girl student ' # Add instance properties
# xl.age=20 # Add instance properties
#
# xm=Pepole() # When you create a new object It's automatic
# print(xm.name) # The direct output is the default value
# xm.name=' Xiao Ming '
# print(xm.name)
# If there is n This object Be instantiated Then you need to add such attributes many times Obviously, it's more troublesome
# init Pass parameters improvement
class Pepole:
def __init__(self,name,sex,age):
'''
Declaration of instance properties
'''
self.name=name
self.sex=sex
self.age=age
pass
def eat(self,food):
'''
The act of eating
:return:
'''
print(self.name+' Like to eat '+food)
pass
zp=Pepole(' Zhang Peng ',' schoolboy ',18)
print(zp.name,zp.age)
zp.eat(' Banana ')
lh=Pepole(' Li Hui ',' schoolboy ',28)
lh.eat(' Apple ')
print(lh.name,lh.age)
xh=Pepole(' floret ',' girl student ',20)
xh.eat(' a mandarin orange ')
print(xh.name,xh.age)
# summary __init__
# 1. python Built in functions With special functions Use a double underscore Wrapped up 【 Magic methods 】
# 2. Is an initialization method Used to define instance properties And initialization data , Called automatically when an object is created You don't have to call... Manually
# 3. Using the mechanism of parameter passing allows us to define more powerful and convenient class

5、 ... and 、self

6、 ... and 、 Magic methods

 (1)str Method

Usually used to view Frequently used information , No, str Print the address of the instance object directly , Yes str When he appeared return

 (2)new Method

new Than init Execute first , Instantiate the class , The return value of the created instance object is given to init The first parameter of , Don't write new Automatically called

class Person:
def __init__(self,pro,name,food):
'''
:param pro: major
:param name: full name
:param food: food
'''
self.pro=pro # Definition of instance properties
self.name=name
self.food=food
print('----init----- Function execution ')
pass
'''
Defining classes
'''
def eat(self,name,food):
'''
Example method
:return:
'''
# print('self=%s',id(self))
print('%s Like to eat %s My major is :%s'%(self.name,self.food,self.pro))
pass
def __str__(self):
'''
Print object Custom object Is the content format
:return:
'''
return '%s Like to eat %s My major is :%s'%(self.name,self.food,self.pro)
pass
def __new__(cls, *args, **kwargs):
'''
Method of creating object instance Every call A new object will be generated cls Namely class Abbreviation
scene : You can control some attributes of the created object It is often used in singleton mode
:param args:
:param kwargs:
'''
print('----new----- Execution of a function ')
return object.__new__(cls) # Here is the real way to create an object instance
pass
pass
# xw Is a new instantiated object
xw=Person(' psychology ',' Xiao Wang ',' durian ')
# print('xw=%s',id(xw))
# xw.eat(' Xiao Wang ',' durian ')
print(xw) # Direct output object
# Summary self characteristic
# self Only defined in a class It only makes sense when the instance method , There is no need to pass in the corresponding parameters when calling But by the interpreter Automatically point to
# self Your name can be changed Can be defined as other names , But the conventional definition has become self
# self refer to Class instance object itself , amount to java in this
# __new__ and __init___ Difference of function
# __new__ Class instantiation method You must return this instance Otherwise, the object will not be created successfully
# __init___ Used to initialize data properties It can also be considered as the construction method of the instance Accept instances of classes self And construct it
# __new__ At least one parameter is cls Represents the class to instantiate , This parameter is instantiated by python The interpreter automatically provides
# __new__ function Execute before __init___ function 

7、 ... and 、 Duel

# There are two figures on the top of the Purple Forbidden battle , Ximen chuixue and ye Gucheng
# attribute :
# name Player's name
# blood Player health
#
# Method :
# tong() Stab each other , The other party loses blood 10 drop
# kanren() Cut each other , The other party loses blood 15 drop
# chiyao() Take a pill , blood 10 drop
# __str__ Print player status .
#
# First step You need to define a class first 【 Character class 】
import time # Import time package
import random
class Role:
def __init__(self,name,hp):
'''
Construct initialization functions
:param name: The role of
:param hp: Blood volume
'''
self.name = name
self.hp = hp
pass
def tongyidao(self,enemy):
'''
Stab people
:param enemy: The enemy
:return:
'''
# Enemy fall 10 blood
enemy.hp -= 10
info = '[%s] Stabbed [%s] A knife ' %(self.name,enemy.name)
print(info)
pass
def kanyidao(self,enemy):
'''
exploit a person
:param enemy: The enemy
:return:
'''
# Enemy fall 15 blood
enemy.hp -= 15
info = '[%s] Cut it [%s] A knife ' %(self.name, enemy.name)
print(info)
pass
def chiyao(self):
'''
Take medicine
:return:
'''
self.hp += 10
info = '[%s] Took a blood tonic , Added 10 Blood dripping ' %(self.name)
print(info)
pass
def __str__(self):
return '%s There is still left %s HP ' %(self.name, self.hp)
# The second step establish 2 individual : Simon blow snow 、 Leaf gu city Instantiate objects
xmcx = Role(' Simon blow snow ', 100)
ygc = Role(' Leaf gu city ', 100)
def xmcx_zhandou(go):
"""
xmcx All possible situations
:param go: The value of random combat
:return:
"""
if go == 1:
xmcx.tongyidao(ygc) # Ximen chuixue stabbed Ye Gucheng +
elif go == 2:
xmcx.kanyidao(ygc) # Ximen chuixue saw Ye Gucheng's knife
else:
xmcx.chiyao() # Ximen chuixue takes medicine
pass
def ygc_zhandou(go):
"""
ygc All possible situations
:param go: The value of random combat
:return:
"""
if go == 1:
ygc.tongyidao(xmcx) # Ye Gucheng stabbed Ximen chuixue
elif go == 2:
ygc.kanyidao(xmcx) # Ye Gucheng saw Ximen chuixue's knife
else:
ygc.chiyao() # Ye Gucheng takes medicine
pass
# for i in range(1,10):
# go = random.randint(1,4)
# print(go)
i = 1 # Rounds
while 1:
xmcx_go = random.randint(1,3) # xmcx Random combat situation
ygc_go = random.randint(1,3) # ygc Random combat situation
xianshou = random.randint(1,2) # Random first hand
print('-------------------- The first %d round ----------------------' % i)
if xmcx.hp <= 0 or ygc.hp <= 0:
break
if xianshou == 1: # xmcx First of all
xmcx_zhandou(xmcx_go)
ygc_zhandou(ygc_go)
else:
ygc_zhandou(ygc_go) # ygc First of all
xmcx_zhandou(xmcx_go)
print(xmcx) # Print object status
print(ygc) # Print object status
time.sleep(2) # Time delay 1s
i += 1
pass
print(' The battle is over ')
if xmcx.hp <= 0:
print('[ Leaf gu city ] win victory ')
elif ygc.hp <= 0:
print('[ Simon blow snow ] win victory ')
# while True:
# if xmcx.hp <= 0 or ygc.hp <= 0:
# break
# xmcx.tongyidao(ygc) # Ximen chuixue stabbed Ye Gucheng
# print(ygc) # Print object status
# print(xmcx)
# print('---------------------------------------------')
# ygc.tongyidao(xmcx)
# print(ygc) # Print object status
# print(xmcx)
# print('---------------------------------------------')
# xmcx.chiyao()
# print(ygc) # Print object status
# print(xmcx)
# print('---------------------------------------------')
# time.sleep(1) # Time delay 1s
# pass
#
# print(' The battle is over ')

8、 ... and 、 Homework

# 1、python How to create objects through classes , Please illustrate with code .
class Student:
def run(self):
print(' Students conduct 2000 Meters of running training ')
pass
pass
xiaoli=Student() # Create an object
xiaoli.run()
# 2、 How to define a method in a class , Please illustrate with code .
# Refer to the above demo
# 3、 Define a fruit class , Then through fruit , Create an apple object 、 Orange object 、 Watermelon objects and add color attributes
class SgClass:
def __init__(self,name,color):
'''
:param name:
:param color:
'''
self.color=color
self.name=name
pass
def __str__(self):
return '%s The color of is 【%s】'%(self.name,self.color)
pass
pg=SgClass(' Apple ',' Red ')
pg.zj=10 # Add object attributes through objects
print(pg)
print('*'*40)
jz=SgClass(' a mandarin orange ',' Orange ')
print(jz)
print('*'*40)
xg=SgClass(' watermelon ',' Black skin ')
print(xg)
# 4、 Please write the code , verification self It's the instance itself .
class Person:
def weight(self):
print('self=%s'%id(self))
pass
# liming=Person()
# liming.weight()
# print(id(liming))
# 5、 Define a Animal class
# (1)、 Use __init__ The initialization method adds initial properties to the object . Such as color , name , Age .
# (2)、 Define animal methods , Such as run,eat Other methods . Such as calling eat Method xx Just eat .
# (3)、 Define a __str__ Method , Output all properties of the object .
class Animal:
def __init__(self,color,name,age):
'''
:param color:
:param name:
:param age:
'''
self.color=color
self.name = name
self.age = age
pass
def eat(self):
print('%s Eating '%self.name)
pass
def run(self):
print('%s Running fast ' % self.name)
pass
def __str__(self):
return '%s The color of is :%s This year, %d Year old '%(self.name,self.color,self.age)
def __del__(self):
print('xhl')
pass
tigger=Animal(' yellow ',' Siberian tigers ',4)
tigger.run()
tigger.eat()
print(tigger)
# del tigger
input('ddz')

Nine 、 Add

(1)__mro__ Method


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved