Object oriented is an abstract programming idea , Is to regard programming as a thing . For the outside world , Things are Use it directly Of , Never mind the internal situation , Programming is about setting what things should do .
Create objects with classes . Class is a class that has the same ** features ( attribute ) and Behavior ( Method )** A general term for things , It's an abstract concept , It's not real . Objects are real things created by classes .
Python2 The middle class is divided into : Classic and new
class Class name ():
Code
# The class name shall meet the identifier naming rules , At the same time, follow the naming convention of big humps
# Classes that do not derive from any built-in types are called classic classes
Object name = Class name ()
# Creating objects is also called instantiating objects
self: The object on which the function is called
# 1. Defining classes
class Washer():
def wash(self):
print(' I can wash ⾐ clothing ')
# <__main__.Washer object at 0x0000024BA2B34240>
print(self)
# 2. Create objects
haier1 = Washer()
# <__main__.Washer object at 0x0000018B7B224240>
print(haier1)
# haier1 Object tone ⽤ example ⽅ Law
haier1.wash()
haier2 = Washer()
# <__main__.Washer object at 0x0000022005857EF0>
print(haier2)
Object properties can be outside the class ⾯ Add and get , Can also be in class ⾥⾯ Add and get .
# Add member attributes outside the class
Object name . Property name = value
# Get object properties outside the class
Object name . Property name
# Get object properties in class
self. Property name
class Washer():
def print_info(self):
# class ⾥⾯ Get instance properties
print(f'haier1 wash ⾐ What is the width of the machine {
self.width}')
print(f'haier1 wash ⾐ The height of the machine is {
self.height}')
# Create objects
haier1 = Washer()
# Add instance properties
haier1.width = 500
haier1.height = 800
haier1.print_info()
stay Python in ,xx() The function of is called magic cube ⽅ Law , It means having Special function Function of .
_init_(): Initialize object
# This method will be called by default when creating objects
#_init_(self) Of self Parameters . No need for developers to deliver ,python The interpreter will pass a reference to the current object
class Washer():
# Functions that define initialization functions
def __init__(self):
# Add instance properties
self.width = 500
self.height = 800
def print_info(self):
# class ⾥⾯ transfer ⽤ Instance attributes
print(f' wash ⾐ What is the width of the machine {
self.width},⾼ Degree is {
self.height}')
haier1 = Washer()
haier1.print_info()
Parameterized _init_() Method :
#⼀ A class can create multiple objects , You can set different initialization properties for different objects by passing parameters
class Washer():
def __init__(self, width, height):
self.width = width
self.height = height
def print_info(self):
print(f' wash ⾐ What is the width of the machine {
self.width}')
print(f' wash ⾐ The machine ⾼ Degree is {
self.height}')
haier1 = Washer(10, 20)
haier1.print_info()
haier2 = Washer(30, 40)
haier2.print_info()
_str_()
# When to make ⽤print When outputting objects , The memory address of the default print object .
# If the class defines __str__⽅ Law , Then it will print from this ⽅ In law return The data of .
class Washer():
def __init__(self, width, height):
self.width = width
self.height = height
def __str__(self):
return' This is Haier wash ⾐ Instructions of the machine '
haier1 = Washer(10, 20)
# This is Haier wash ⾐ Instructions of the machine
print(haier1)
_del_()
# When deleting objects ,python The interpreter will also call by default _del_() Method
class Washer():
def __init__(self, width, height):
self.width = width
self.height = height
def __del__(self):
print(f'{
self} Object has been deleted ')
haier1 = Washer(10, 20)
# <__main__.Washer object at 0x0000026118223278> Object has been deleted
del haier1
Combine attributes with ⽅ The Dharma script writes about ⾥⾯ The operation of is encapsulation + Encapsulation can be attributes and ⽅ Can't add private permissions
stay Python in , All classes inherit by default object class ,object A class is a top-level class or a base class ; other ⼦ The class is called pie ⽣ class .
class Class name (object):
Code
#⽗ class A
class A(object):
def __init__(self):
self.num = 1
def info_print(self):
print(self.num)
#⼦ class B
class B(A):
pass
result = B()
result.info_print()# 1
(1) When ⼀ More than one class ⽗ Class time , By default ⽤ The first ⼀ individual ⽗ Class with the same name ⽅ Law .
(2)⼦ Classes and ⽗ Class has properties with the same name and ⽅ Law , By default ⽤⼦ Class with the same name ⽅ Law .
class Master(object):
def __init__(self):
self.kongfu = '[ Gufa pancake fruit ⼦ with ⽅]'
def make_cake(self):
print(f' shipment ⽤{
self.kongfu} Make pancakes and fruit ')
class School(object):
def __init__(self):
self.kongfu = '[⿊⻢ Pancake fruit ⼦ with ⽅]'
def make_cake(self):
print(f' shipment ⽤{
self.kongfu} Make pancakes and fruit ')
class Prentice(School, Master):
def __init__(self):
self.kongfu = '[ Original pancake fruit ⼦ with ⽅]'
def make_cake(self):
# If it is adjusted first ⽤ 了 ⽗ Class and ⽅ Law ,⽗ Class properties will override ⼦ Class properties , So in tune ⽤ Before attributes , First tune ⽤⾃⼰⼦ Class initialization
self.__init__()
print(f' shipment ⽤{
self.kongfu} Making pancake fruit ⼦')
# transfer ⽤⽗ class ⽅ Law , But in order to ensure that ⽤ So did you ⽗ Attributes of a class , Must be in tune ⽤⽅ Pre regulation ⽤⽗ Class initialization
def make_master_cake(self):
Master.__init__(self)
Master.make_cake(self)
def make_school_cake(self):
School.__init__(self)
School.make_cake(self)
daqiu = Prentice()
daqiu.make_cake()
daqiu.make_master_cake()
daqiu.make_school_cake()
daqiu.make_cake()
super(): Call the superclass method
send ⽤super() Sure ⾃ Dynamic search ⽗ class . transfer ⽤ Sequence following __mro__ The order of class properties .⽐ More suitable for single inheritance ⽤.
stay Python in , Can be instance properties and ⽅ Can't set private permissions , That is, set an instance property or instance ⽅ Law does not inherit to ⼦ class . Setting private permissions ⽅ Law : In the attribute name and ⽅ Before legal name ⾯ Add two underscores __
self._money=200000
(1) Use get__xx Get private properties , Use set__xx Modify private properties
# Get private properties
def get_money(self):
return self.__money
# Modify private properties
def set_money(self):
self.__money = 500
Pass on ⼊ Different objects , production ⽣ Different results
Polymorphism refers to ⼀ There are many forms of such things ,(⼀ There are more than one abstract class ⼦ class , because ⽽ The concept of polymorphism depends on inheritance ).
Definition :
(1) Polymorphism is ⼀ The seed makes ⽤ Object's ⽅ type ,⼦ Class rewriting ⽗ class ⽅ Law , transfer ⽤ Different ⼦ Class object ⽗ class ⽅ Law , It can produce ⽣ There are different ways ⾏ result
(2) benefits : transfer ⽤ flexible , With polymorphism , It's easier to write a pass ⽤ Code for , Make a pass ⽤ Programming for , To adapt to the changing needs !
Implementation steps :
(1) Definition ⽗ class , And provide public services ⽅ Law
(2) Definition ⼦ class , And rewrite ⽗ class ⽅ Law , Pass on ⼦ Class object ⽤ person , You can see the difference ⼦ Class execution ⾏ Different effects
class Dog(object):
def work(self):
#⽗ Class provides system ⼀ Of ⽅ Law , Even if it's empty ⽅ Law
print(' Where to hit ...')
class ArmyDog(Dog):
# Inherit Dog class
def work(self):
#⼦ Class rewriting ⽗ Class name ⽅ Law
print(' follow up the enemy ...')
class DrugDog(Dog):
def work(self):
print(' Trace drugs ...')
class Person(object):
def work_with_dog(self, dog):
# Pass on ⼊ Different objects , Of board ⾏ Different codes , That's different work function
dog.work()
ad = ArmyDog()
dd = DrugDog()
daqiu = Person()
daqiu.work_with_dog(ad)
daqiu.work_with_dog(dd)
Class properties are Class object The attributes that you have , It is shared by all instance objects of the class . Class properties can make ⽤ Class object or instance object access .
The data recorded by the instance of class is always maintained ⼀ To the hour , The definition is Class properties . Instance properties require each object to be its Separate development ⼀ Memory space To record data ,⽽ Class attributes are common to all classes , Only occupy ⽤⼀ Memory , More memory saving .
Class properties can only be modified through class objects , Cannot be modified by an instance object , If you modify class properties through an instance object , Indicates the creation of ⼀ Instance properties .
Class method is the ⼀ A formal parameter is a parameter of a class object ⽅ Law , need ⽤ Decorator @classmethod To identify it as a class ⽅ Law , For classes ⽅ Law , The first ⼀ Parameter must be a class object ,⼀ Generally cls As a first ⼀ Parameters .
Static methods need to pass Decorator @staticmethod Come on in ⾏ modification , static state ⽅ Method requires neither passing class objects nor instance objects ( No formal parameters self/cls). static state ⽅ Methods can also be accessed through instance objects and class objects .
class Dog(object):
@staticmethod
def info_print():
print(' This is a ⼀ A dog ,⽤ Create a dog instance ...')
wangcai = Dog()
# static state ⽅ Law can make ⽤ Object access ⼜ You can make ⽤ Such access
wangcai.info_print()
Dog.info_print()
Product design requirements :
(1) Baking time and corresponding state
(2) seasoning : Users can add as they wish
Step analysis :
The earth ⽠ Properties of
The earth ⽠ Of ⽅ Law
# Defining classes
class SweetPotato():
def __init__(self):
# Baking time
self.cook_time = 0
# The earth ⽠ The state of
self.cook_static = '⽣ Of '
# Seasoning list
self.condiments = []
def cook(self, time):
""" Roast the ground ⽠ Of ⽅ Law """
self.cook_time += time
if 0<= self.cook_time<3:
self.cook_static = '⽣ Of '
elif 3<= self.cook_time<5:
self.cook_static = ' And a half ⽣ Not familiar with '
elif 5<= self.cook_time<8:
self.cook_static = ' Ripe '
elif self.cook_time>= 8:
self.cook_static = ' It's burnt '
def add_condiments(self, condiment):
""" Add seasoning """
self.condiments.append(condiment)
def __str__(self):
return f' This place ⽠ Roasted {
self.cook_time} minute , Status is {
self.cook_static}, The spices added are {
self.condiments}'
digua1 = SweetPotato()
print(digua1)
digua1.cook(2)
digua1.add_condiments(' The soy sauce ')
print(digua1)
digua1.cook(2)
digua1.add_condiments(' chili ⾯⼉')
print(digua1)
digua1.cook(2)
print(digua1)
digua1.cook(2)
print(digua1)
demand : Put furniture smaller than the remaining area of the house into the house
class Furniture():
def __init__(self, name, area):
# Furniture name
self.name = name
# Furniture covers ⾯ product
self.area = area
class Home():
def __init__(self, address, area):
# Location
self.address = address
# House ⾯ product
self.area = area
# The remaining ⾯ product
self.free_area = area
# Furniture list
self.furniture = []
def __str__(self):
return f' room ⼦ be seated {
self.address}, Covers an area of ⾯ product {
self.area}, The remaining ⾯ product {
self.free_area}, Furniture has {
self.furniture}'
def add_furniture(self, item):
""" Accommodating furniture """
if self.free_area>= item.area:
self.furniture.append(item.name)
# Furniture removal ⼊ after , Housing surplus ⾯ product = Previous remaining ⾯ product - The furniture ⾯ product
self.free_area -= item.area
else:print(' The furniture is too ⼤, The remaining ⾯ Jibu ⾜,⽆ The law holds ')
bed = Furniture(' double ⼈ The bed ',6)
jia1 = Home(' Beijing ',1200)
jia1.add_furniture(bed)
sofa = Furniture(' Sofa ',10)
jia1.add_furniture(sofa)
ball = Furniture(' Basketball Court ',1500)
jia1.add_furniture(ball)