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

Python16- object oriented & class and object & constructor

編輯:Python

One 、 object-oriented

1. Concept

1.1 Object oriented design idea

Object oriented is based on the philosophical view that everything is an object . stay Python in , Everything is the object

 Illustrate with examples :
Case a : I would like to have a large plate of chicken
Process oriented object-oriented
1. Go shopping by yourself 1. Entrust a person who can bargain to help buy vegetables
2. Choose your own dish 2. Entrust a temporary worker to help choose dishes
3. Cook your own food 3. Entrust a cook to help with cooking
4. Start eating by yourself 4. Start eating by yourself
Case 2 : Xiao Ming is a computer Xiaobai , I want a computer , After the parts are purchased, they need to be transported home , After assembly, open the computer to play games
Process oriented object-oriented
1. Xiao Ming adds computer knowledge 1. Entrust a friend who knows computer ( Lao Wang ) To help buy parts
2. Xiao Ming goes to buy parts 2. Entrust a person who can run errands to buy parts
3. Xiao Ming takes the parts home 3. Entrust a person who can assemble computers to help Xiao Ming assemble computers
4. Xiao Ming assembles the computer 4. Xiao Ming turns on the computer himself , Start playing games
5. Xiao Ming starts up to play with the computer
Case three : A white Audi Q5 Driving on the Beijing Tibet Expressway
Audi here Q5 It's an object , Beijing Tibet expressway is also an object

1.2 The difference between procedural and object-oriented 【 Interview questions 】

Process oriented

In life cases :

 A way of thinking about problems , When thinking about problems , Focus on how the problem is solved step by step , Then solve the problem yourself

In the program :

 The code is executed from top to bottom
The relationship between modules should be as simple as possible , Relatively independent in function
The first mock exam is the order of each module. 、 Three basic structures of selection and circulation
The specific method of modularization is to use subroutine
The program flow is determined when the program is written

object-oriented

In life cases :

 It's also a way of thinking about problems , Focus on finding 【 A specific individual with special functions , Then entrust the individual to do something 】, We call this individual the object , Everything is the object
It is a thought more in line with human thinking habits 【 A lazy mind 】, Can simplify complex things , Turn a programmer from a performer to a commander

In the program :

 Put the data and how to operate it together , As an interdependent whole —— object
1》 Abstract the commonness of similar objects , Formative class
2》 Most of the data in the class , It can only be handled by the methods of this class
3》 Classes relate to the outside world through a simple external interface , Objects communicate with each other through messages
4》 The procedure flow is determined by the user in use
5》 Use object-oriented development , First, find the object with the required function , If the object does not exist , Then create an object with this function
Be careful : Object orientation is just an idea , It's not a programming language , Nor will it bind to the programming language

The advantages and disadvantages of process oriented and object-oriented 【 Interview questions 】

Process oriented :

 advantage : Better performance than object-oriented , It costs a lot , Compare the consumption of resources , For example, single chip microcomputer 、 Embedded development is generally process oriented development , Because performance is the most important factor
shortcoming : No object-oriented and easy to maintain , Easy to reuse , Easy to expand

object-oriented :

 advantage : Easy maintenance , Easy to reuse , Easy to expand , Because of the encapsulation of object-oriented , Inherit , Polymorphism , You can design low coupling systems , Make the system more flexible , Easier to maintain
shortcoming : Performance is lower than process oriented

Python It's a language for , The characteristics of object-oriented language : encapsulation , Inheritance and polymorphism

fall : object-oriented

Eat shit : Process oriented

2. Classes and objects

2.1 Concept

class : A collection of entities with special functions 【 Groups 】, It is abstract.

object : In a class , An entity with special functions , Able to help solve specific problems 【 Objects are also called instances 】, It is concrete.

The relationship between the two : Class is used to describe the common characteristics of a class of objects , The object is the concrete existence of the class ( Inclusion relation )

problem : Object first or class first ?

【 To say , however , Usually in the program , Is to define the class first , Then create objects through classes 】

give an example :

 class object
people Zhang San 、 Li Si 、 Wang Ma Zi 、 Yang Yang ...
SuperHero batman 、 spider-man 、 Captain America ...
Courier Shun Feng 、 Tact 、 sto 、 Rhyme ...

Help you understand : Class is also a data type , It's just custom 【 System class ValueError,NameError….】, With what I have learned int,str,bool And so on . Instantiating an object with a class is equivalent to defining the variables of a class

num = 10
print(type(num)) # <class 'int'>
# Defining classes Person
p = Person()
print(type(p)) # <class '__main__.person'>

2.2 Class definition and object creation

Format :

class Class name ():

 The class body

explain :

a.Python Use in class Keyword definition class
b. As long as the class name is a legal identifier , But ask for : Follow the big hump nomenclature , Such as :KeyError,ValueError,NameError,IndexError…….
c. Try to connect one or more meaningful words
d. The existence of class bodies is reflected by indentation
e. Class body generally contains two parts : Description of class characteristics and behavior
# One 、 The definition of a class
print("start~~~~~")
class MyClass1():
print("1111")
class MyClass2():
print("2222")
class MyClass3():
print("3333")
class MyClass4():
print("4444")
print("over~~~~~")
"""
Be careful :
a. In the same py In file , You can define multiple classes at the same time , however , In complex requirements , Generally, a module defines a class
b.class xxx(): Represents the declaration of a class , Try to follow the naming method of the big hump ,() It can be omitted , But in Python3.x in , Advice and
c. The indented contents are called class bodies 【 The realization of the class 】, In which the members of the class are defined 【 Description of class characteristics and behavior 】,
Once a class is defined , The members of the will be loaded
"""
# Two 、 Object creation / Class instantiation / Object instantiation
# grammar : Class name (....)
num = 10
print(type(num)) # <class 'int'>
print(MyClass1) # <class '__main__.MyClass1'>
mc1 = MyClass1()
print(type(mc1)) # <class '__main__.MyClass1'>
print(id(mc1))
print(mc1)
mc2 = MyClass1()
print(mc2)
mc3 = MyClass1()
print(mc3)
"""
Be careful :
a. Suppose you define a class MyClass, Use it directly MyClass Represents the class name , It also represents a data type , Use MyClass() Represents the creation object
b.m = MyClass(),m The essence is a variable , The type of the variable is MyClass type , Variable m The address of the created object is stored in
c.MyClass() The code executes once , It means to create a new object
d. In general , One class can create countless objects
"""

2.3 Class design

Just care 3 things

 The name of the thing ( Class name ): human beings (Person)
features : height (height)、 Age (age)—————》 Noun ———》 Variable
Behavior : run (run)、 fight (fight)———————》 Verb ————》 function
Initial learning , Extract classes by refining gerunds

3. Members in class

3.1 Define and access

# One 、 Class
# 1. Defining classes
class Person():
# The class body : Characteristics and behavior
# 2. features : Variable
# 3. Behavior : function
"""
About self:
a.self, own , Oneself , Represents the current object
b. Which object calls the function , Among them self Indicates which object
c.self As part of the formal parameter , Don't omit , When calling functions at the same time , There's no need to manually give self The ginseng
d. When a function is called , The system will automatically transfer the current object to self
e.self In fact, it is not a keyword , But often self, Represents the current object
"""
def eat(self,sth):
print(f"eating {sth}")
def run(self):
print('running',id(self))
# Two 、 Access the members of the class
# 1. Call the function in the class , grammar : object . function ( Actual parameters )
per1 = Person()
print(f"per1 The address of :{id(per1)}")
per1.run()
per1.eat("apple")
per2 = Person()
print(f"per2 The address of :{id(per2)}")
per2.run()
per2.eat("food")
# 2. Class characteristics 【 Variable / attribute 】
per = Person()
per.name = " Zhang San "
per.age = 18
print(per.name,per.age)
"""
Be careful :
a. Members of a class cannot be accessed directly in the class , You need to access... Through objects or classes
b. Class 【 function 】 It can be defined directly inside the class , Class characteristics 【 Variable 】 It can be bound directly
"""

3.2 Dynamic binding properties and restricted binding

# 1. Dynamic binding of object attributes
class Person():
def show(self):
print(f" full name :{self.name}, hobby :{self.hobby}, achievement :{self.score}")
# grammar : object . attribute = value , Custom attribute name
per = Person()
per.name = " Zhang San "
per.age = 18
per.hobby = " Sing a song "
per.score = 100
print(per.name,per.age)
per.show() # self--->per
# Be careful 1: Dynamically bind attributes to an object , It has nothing to do with other objects
# per2 = Person()
# print(per2.name)
# Be careful 2: Multiple objects are bound with properties with the same name , The attribute value of an object changes , It has no effect on the properties of other objects
per2 = Person()
per2.name = " Li Si "
per.name = "tom"
print(per2.name)
print("*" * 50)
# 2. Restrict dynamic binding of object properties
class Person():
# __slots__ = (' Field 1',' Field 2'.....), Fields in tuples represent fields that allow dynamic binding
# Be careful : If only one attribute needs to be bound , be __slots__ = (' Field ',)
__slots__ = ("name",'hobby','score')
def show(self):
print(f" full name :{self.name}, hobby :{self.hobby}, achievement :{self.score}")
per = Person()
per.name = " Zhang San "
per.hobby = " Sing a song "
per.score = 100
# per.age = 18 # AttributeError: 'Person' object has no attribute 'age'
per.show()

4. Constructors

 Create the object first , Then use direct assignment 【 Dynamic binding properties 】 Method to bind attributes to objects , have access to , But the code is complicated , In general , Many classes tend to create objects with an initial state , You can define a function in a class , The name is __init__, This particular function is called a constructor , It is mainly used to create objects and initialize their data
emphasize : Constructors include __new__ and __init__
Constructors , Also known as constructors , When you create an object , Automatically called functions
grammar :
def __init__(self):
The body of the function
# 1. Before using constructor
class Person1():
__slots__ = ('name','age')
p1 = Person1()
p1.name = 'aaa'
p1.age = 10
p2 = Person1()
p2.name = 'bbb'
p2.age = 15
p3 = Person1()
p3.name = 'ccc'
p3.age = 17
print("*" * 50)
# 2. How constructors work
"""
Be careful :
a. If no constructor is defined in the class , When you create an object , The system will automatically call the constructor
b. The constructor contains :__new__() and __init__()
c.p = Person(). When the actual code is executed ,p What you get is __new__ The return value of
d. If you will __new__ Define it explicitly , be __new__ The return value of must be an object :super().__new__(cls)
e. First call __new__, And then call __init__
f. working principle : Through the first __new__ Create an object , Then pass the object to __init__ Medium self, To initialize
g.__new__() and __init__() Is automatically called during object creation , No manual call required
"""
class Person2():
__slots__ = ('name', 'age')
# a.__new__: It means the process of growing from nothing , Represents the creation object
def __new__(cls, *args, **kwargs):
print("new~~~~~")
# super().__new__(cls) Means to create an object
return super().__new__(cls)
# b.__init__: Denotes initialization , Initialization by __new__ Objects created
def __init__(self,name,age):
print("init~~~~~~")
# Dynamic binding properties
self.name = name
self.age = age
p21 = Person2('aaa',10)
print(p21)
print(p21.name,p21.age)
p22 = Person2('bbb',15)
print(p22)
print(p22.name,p22.age)
p23 = Person2('ccc',18)
print(p23)
# 3. The actual use
# Be careful : In actual use , Just define the in the constructor __init__, When you create an object , Need and __init__ The parameters match
class Person3():
__slots__ = ('name', 'age')
def __init__(self,name,age):
self.name = name
self.age = age
p31 = Person3('aaa',10)
print(p31)
print(p31.name,p31.age)

5. Comprehensive practice

# demand : Back in school , Mr. Wang asked the students 【 Xiao Ming , floret , Xiao Li 】 Introduce yourself
# Introduce the name , Age , hobby , A talent show
"""
analysis :
The teacher class :
features : full name
Behavior : Give Way .... Introduce yourself
Students :
features : full name , Age , hobby
Behavior : Introduce yourself , A talent show
"""
class Teacher():
__slots__ = ("name",)
def __init__(self,name):
self.name = name
# stu It means the student object , It's not a string
def let_stu_introduce(self,stu):
# self It means the object of Mr. Wang ,stu It means xiaoming The object of
print(self.name + " Give Way " + stu.name + " Introduce yourself ")
# Let students carry out their own behavior
stu.introduce()
if stu.name == " floret ":
stu.sing()
elif stu.name == " Xiao Li ":
stu.dance()
elif stu.name == " Xiao Ming ":
stu.lie()
class Student():
__slots__ = ("name","age","hobby")
def __init__(self,name,age,hobby=" Study "):
self.name = name
self.age = age
self.hobby = hobby
def introduce(self):
print(f" Hello everyone , I am a {self.name}, This year, {self.age}, hobby :{self.hobby}")
def sing(self): # floret
print(" Lady ~~~~ Ah ")
def dance(self): # Xiao Li
print(" square dance ")
def lie(self): # Brag makes you
print(" My family has thousands of sheep , Thousands of cows ~~~~~")
# Create a teacher's object
wang = Teacher(" Teacher wang ")
# Create student objects
xiaoming = Student(" Xiao Ming ",8," Brag makes you ")
xiaohua = Student(" floret ",5," Sing a song ")
xiaoli = Student(name=" Xiao Li ",age=10,hobby=" dance ")
# Let the teacher carry out his own behavior
wang.let_stu_introduce(xiaoming)
wang.let_stu_introduce(xiaohua)
wang.let_stu_introduce(xiaoli)

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