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

Advanced Python Programming -- object oriented

編輯:Python

Catalog

  • 1. object-oriented
  • 2. Magic methods
  • 3. Homework :


1. object-oriented

# Everything is object 
# Method of encapsulating code , More advanced packaging 
# object-oriented , Developed from a process oriented foundation , It is more flexible and extensible than process oriented 
# Process oriented : object-oriented Programming is a way to solve problems , It refers to different solutions to the same problem 
# Put the elephant in the refrigerator :3 Step 
# 1. Open the refrigerator door 
# 2. Put the elephant in the refrigerator 
# 3. Close the refrigerator door 
# Student management system is process oriented , Add, modify and delete query tools are encapsulated into functions independently , Finally, call different functions in order 
# Daily thinking to do 
# Process oriented thinking 
# 2. Put the elephant in the refrigerator 
# 3. Close the refrigerator door 
# 1, Open the refrigerator door 
# When you use it 1. Open the refrigerator door 2. Put the elephant in the refrigerator 3. Close the refrigerator door 
# Assembly line thinking wev Automatic open class Linear code Realize Baidu search 
# 1. Open Google browser 2. Visit Baidu 3. Find the input box and enter the search content 4. Find the search button and click 
# object-oriented : Create an object Leave what you want to do to this object 
# Create an object 
# Refrigerator objects 
# The refrigerator has a way to open the door 
# There are ways to pack things in the refrigerator ( Elephant , snacks , drinks )
# There are ways to close the refrigerator 
# Programming solutions to problems 
# object-oriented : Focus on who will do 
# Process oriented : An assembly line , A set of processes from beginning to end solve problems in order 
# object-oriented , Process oriented Way better : Learning thinking Simple code Uncomplicated process Process oriented Element localization ( Tracking error )
# 1. Open Google 2. Visit the landing page 3. Find the input box and enter the user , Click password to login , Search for mobile phones , Add mobile phone to shopping cart 
# A complex process Object oriented thinking to do 
# object-oriented pom Page object 
# Log in to a page object The login page Find the user name input box Find the password input box Find the login button The whole process of login Added a process Verification Code 
# Add to cart page Look for color Find the quantity 
# There are several students , The first student :
# petty thief , Age 18 year , Gender female Can play games , Can play badminton 
# Xiao Ming , Age 20 year , Gender male , Can eat chicken , Can play basketball 
# Crooked , Age 60 year , Gender female , Can cook , Can knit sweaters 
# Process oriented writing 
# Define a Xiao Li , Age 18 year , Gender female Can play games , Can play badminton 
# Define a Xiao Ming , Age 20 year , Gender male , Can eat chicken , Can play basketball 
# Define a curve , Age 60 year , Gender female , Can cook , Can knit sweaters 
# Get Xiao Li's information 
# Just call Xiao Li's function 
# Xiao Ming's function 
# Object oriented writing 
# Student object 
# Student : name , Age , Gender Can play games Can play badminton Can eat chicken Can play basketball Can cook Can knit sweaters 
# establish (' petty thief ',18, Woman ) Can play games Can play badminton 
# (' Crooked ',60, Woman ) Can cook Can knit sweaters 
# How many students are created How many students do you give him How many skills do students have 
# object-oriented : Learn two names 
# class : A general term for things with common characteristics or the same behavior 
# birds : features : With wings , There are two feet , There's a pair of eyes , The heart has four chambers , The body temperature is constant 
# Behavior : Can fly , Can eat worms 
# Features are called : attribute 
# The act is called : Method 
# Class is abstract It can't refer to specific things , Is a general template 
# object : Something specific Specifically, the parrot in aunt's house downstairs , The sparrow of Xiao Wang's family next door Different specific objects 
# Defining classes 
''' class Class name : Class properties Class method def Method 1(self): pass def Method 2(self): pass Class properties : The characteristics of things Class method : The behavior of things Class name : The first initial is capitalized Bridge '''
# game , There are several cats in the game , All are 20kg, The color is white , So I have a few 20 Jin white cat , A white cat can catch mice 
# A white cat can eat fish , A white cat can eat fish, catch mice and make holes 
# Write ? Process oriented ? Definition 3 Cats 
# object-oriented : Create a template That is class 
# Create every cat , weight , Color , Give the cat a name and change it by yourself 
# use init Initialization function effect Just create class objects , It will carry out this init
# def test( Parameters , Parameters ):
# Variable name = Parameters 
# name It's Emerald flowers weight yes 20 color It's black, white and grey 
class Cat:
def __new__(cls,*args,**kwargs):
return object.__new__(cls)
def __init__(self,name,weight,color):
# The emerald flower is assigned to self.name, therefore self.name It's Emerald flowers . then self It represents the object itself , therefore tom1.name Cui Hua 
self.name = name
self.weight = weight
self.color = color
def catch(self):
print(f'{
self} Small {
self.color} Cat catches mouse ')
def eat(self):
print(' Little white cat likes fish ')
def cave(self):
print(' Little white cat can make holes ')
def __str__(self):
return f' This is the description information of an object :{
self.name}{
self.color} The sad story of the cat '
def __del__(self):
print(f'{
self.name} The kitten hung up ')
# All the characteristics of white cats 
# Class cannot be used directly 
# Create specific objects That is, instantiating objects Object name = class () Object name . Method name Object name . attribute 
# tom Little white cat 
# self I do not know! Breakpoint look self Like object address self It seems to be an object 
# Created an object self Can distinguish which object you are 
tom1 = Cat()
tom1.catch()
# Create a specific cat that can catch mice 
print('-'*50)
tom2 = Cat()
tom2.eat()
# Create a specific cat that can eat fish 
print('-'*50)
tom3 = Cat()
tom3.eat()
tom3.catch()
tom3.cave()
# Create a specific cat that can eat fish, catch mice and make holes 
# This is a 3 Cats I'm not sure if it's 3 Cats Monitor whether there are three cats ? id testing 
print(tom1,id(tom1))
print(tom2,id(tom2))
print(tom3,id(tom3))
# Cats are white , Can you make special , There is a cat with mutation Black and white cat 
# Change the attributes of cats 
tom1 = Cat()
tom1.cat_color = ' Black and white '
tom1.catch()
tom2 = Cat()
tom2.catch()
# tom1 Namely self
tom1 = Cat(' Cui Hua ','20',' Black and white grey ')
print(' The name is {} Small {} The cat story '.format(tom1.name,tom1.color))
print(tom1)
# to want to tom1 What I print out is my own customized thing 
tom1.catch()
tom2 = Cat(' Under the moon ','20',' The cat under the moon ')
print(' The name is {} Small {} The cat story '.format(tom2.name,tom2.color))
# When will it be used in the project init function Create an object Use the content in the object I must do something before 
# What must be done is written in init Inside 
# Database configuration Database links 

2. Magic methods

# use init Initialization function effect Just create class objects , It will carry out this init
# __str__ Object description method , As long as it's defined __str__ Method , Object will print the return
# __del__ Destroy object , Whether you write or not del function , Will be destroyed 
# __new__ Create object of class 

3. Homework :

# subject : Go to the bank to deposit and withdraw money 
# Two dogs Bank Account 123456789 balance 500 Want to save money 200
# False bamboo Bank Account 23456789 balance 5 Want to withdraw money 100
# autumn waters Bank Account 3456789 balance 5 Billion Want to save money 1 Billion 
class Bank:
def __init__(self,username,card_no,balance):
self.username = username
self.card_no = card_no
self.balance = balance
# Deposit money 
def deposit(self,amount):
print('{} You are here to save money , save {}'.format(self.username,amount))
self.balance = self.balance + amount
# Withdraw money 
def withdrawal(self,amount):
print(' I'm here to withdraw money , take {}'.format(amount))
if self.balance >= amount:
self.balance = self.balance - amount
else:
print(' Thinking about money is crazy , Step on it ')
def __str__(self):
return f' I am a {
self.username}, My account {
self.card_no}, The balance of my {
self.balance}'
# Original 500, Save 200, The balance is unchanged 
ergou = Bank(' Two dogs ','123456789','500')
ergou.deposit(200)
print(ergou)
# Original account 5 Yuan Want to take 100 block No way Tips Judge that the account balance is greater than or equal to the withdrawal balance , Let you take , Remember to subtract from your account , Let you take , Otherwise, I'm crazy about money 
xuzhu = Bank(' False bamboo ','123456789','5')
xuzhu.withdrawal(100)
print(xuzhu)
# The rest of the logic 
# Two dogs save money , After saving, the money in the account did not increase 
# False bamboo withdraws money , He still has money after withdrawing more than his balance 
# object-oriented 
# Classes and objects Create a class Only instantiated objects can be used 
# self It represents your own 
# init function del str
# 1.# Lose weight and grow up Classes and objects 
# Xiao Ming weight 80 kg 160 Jin 
# 1. Xiao Ming runs every time Will lose weight 0.5 kg 
# 2. Every time you eat Weight gain 1 kg 
# name Stars Cold lamp 
class Person:
def __init__(self,name,weight):
self.name = name
self.weight = weight
# Give me a number of times to lose weight 
def run(self,num):
print('%s Love running , Running to lose weight , reduce 0.5 Jin '%(self.name,self.weight))
self.weight = self.weight - 0.5*num
# When eating Give me a number Not sure 
def eat(self,num):
print('%s Love to eat , Eat and get fat , Fat is fat 1 Jin '%(self.name,self.weight))
self.weight=self.weight+1*num
def __str__(self):
return " My name is %s, weight %.2f"%(self.name,self.weight)
# Create objects Object name = Class name ()
x = Person(' Stars ',80)
print(x)
# Eat something How to eat Every time you eat Weight gain 1 Jin The original weight should be added 1 Jin 
x.eat()
print(x)
x.run()
print(x)
# Stars eat three meals a day ,3 Don't even exercise ,10 Ton 
x.eat()
x.eat()
x.eat()
x.eat(3)
print(x)
x.run(3)
print(x)# 

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