Python study notes four: object-oriented programming (OOP)

1.OOP(Object Oriented Programming)

  • thought:

    • Solve engineering problems with modular thinking
    • Process Oriented vs Object Oriented
    • From process-oriented to object-oriented
    • For example, I want to open a school:
      • lecturer
      • head teacher
      • student
      • Classroom
      • 。。。。。。
  • Common nouns

    • OO: Object Oriented
    • OOA: analysis
    • OOD: Design
    • OOP: Programming
    • OOI: Implementation
    • OOA -> OOD -> EOI
  • Class vs object (the two are attribution relationships, but not composition relationships)

    • Class: Abstract, describing a collection, focusing on commonality (student class)
    • Object: Concrete, describing the individual (Mr. Zhang)
  • The content of the class:

    • Action, function
    • Attributes, variables
  • Define the class: class keyword

  • Class naming:

    • Follow the big hump (the first letter of each word is capitalized)
    • Capitalize the first letter
# 定义学生类,和几个学生

class Student():
    # 此处定义一个空类
    # pass是关键字,表示占位用的,无意义(养成好习惯)
    pass
# 定义一个对象
zhangsan = Student()
# 定义时,全体缩进
class PythonStudent():
    name = "Nobody"
    age = 20
    course = "Python"
    '''
    定义类中的函数,一般要有self关键字
    其余跟普通函数基本相同
    
    '''
    
    def giveMoney(self):
        print("show me the money")
        return None
    
lisi = PythonStudent()
print(lisi.name)
print(lisi.age)
print(lisi.course)

Nobody
20
Python

2. Attributes of the class

# 类的例子
# 注意类的定义
class Student():
    # name,age是类的变量
    name = "amy"
    age = 20
    
    def sayHi(self):
        print("类的属性")
        return None
    
    
    def sayHello(koko):
        print("将self替换为koko")
        return None 
# 实例化
lisi = Student()

print(lisi)

2.1 self

  • self can be replaced by another name
  • self is not a keyword
  • Role refers to itself
# self举例

# 实例调用函

honghong = Student() # 实例化yaoyao

# 让honghong跟我打招呼
# honghong调用sayHi没有输入参数
# 因为迷人实例作为第一个传入的参数,即honghong代替self
honghong.sayHi()

# 错误的案例:
# a = "你好"
# honghong.sayHi(a)

Class attributes

#这个案例说明self的名称可以更改,实际上self为形参
honghong.sayHello()

Replace self with koko

2.2 The problem of class variable scope

  • Class variables: variables belonging to the class itself
  • Instance variables: variables that belong to the instance
  • A summary of the following two cases:
    • After defining the properties of the instance, when accessing the properties of the instance, priority is given to accessing the properties of the instance itself; if not, then the properties of the class are accessed.
# 案例1:

# 注意类的定义
class Student():
    
    # name,age是类的变量
    name = "amy_77"
    age = 20
    
    def sayHi(self):
        print("My Name is {}, i am {} years old".format(self.name,self.age))
        self.age = 21
        self.name = "NoName"
        return None

# 此案例说明,实例变量可以借用类的变量
qianqian = Student()
qianqian.sayHi()

My Name is amy_77, i am 20 years old

# 案例2:

# 注意类的定义
class Student2():
    
    # name,age是类的变量
    name = "amy_77"
    age = 20
    
    def sayHi(self, n, a ):  # 实例变量,给self定义自己的变量name和age
        self.name = n
        self.age = a
        
        print("My Name is {}, i am {} years old".format(self.name,self.age))
        return None

# 此案例说明,实例变量可以借用类的变量
qianqian = Student2()

# 注意观察下面语句打开和关闭后的区别
# qianqian.sayHi("yuanyuan", 30)

print("My Name is {}, i am {} years old".format(Student2.name,Student2.age))
print("My Name is {}, i am {} years old".format(yuanyuan.name,yuanyuan.age))

#若果访问实例的属性没有定义,则自动访问类的属性
# 如果类也没有定义,则报错

My Name is amy_77, i am 20 years old
My Name is amy_77, i am 20 years old

2.3 Access to the properties of the class

  • If you force access to the attributes of the class in the class, you need to use __class__ (two underscores before and after)
  • Class method:
    • When defining the method of the class, there is no self parameter
    • Only the content of the class is allowed in the method of the class
    • Two methods
      • ClassName
      • __ class __ (two underscores before and after)
class Student3():
    
    # name,age是类的变量
    name = "amy_77"
    age = 20
    
    def sayHi(self):
        print("My Name is {}, i am {} years old".format(self.name,self.age))
        return None
    
    
    # SOS是类的方法
    def SOS():
        # 类方法中不允许访问实例的任何内容
        #print("My Name is {}, i am {} years old".format(self.name,self.age))
        
        # 如果访问想要类的内容,有下面两种方法:
        print("My Name is {}, i am {} years old".format(Student3.name,__class__.age))
        return None
    
# 体验类的方法
s = Student3()
s.sayHi()

# 调用类方法的例子
Student3.SOS()
# SOS() takes 0 positional arguments but 1 was given
# SOS()接受0个位置参数,但给出了1个

My Name is amy_77, i am 20 years old
My Name is amy_77, i am 20 years old

2.4 Constructor

  • When the class is instantiated, some basic initialization work is performed
  • Use special names and wording
    • Automatically executed at instantiation
    • Is the "first" function to be executed at instantiation
class Student4():
    name = "Everybody"
    age = 0
    
    # 构造函数名称固定,写法相对固定
    def __init__(self):
        print("我是一个构造函数")


qianqian = Student4()
print("*******************")
print(qianqian.name)
print(qianqian.age)

I am a constructor


Everybody
0

3. Three characteristics of object-oriented

  • inherit
  • Encapsulation
  • Polymorphism

3.1 Inheritance (Python does not repeat the wheel)

  • The word class can use the content or behavior defined by the parent class, etc.
  • Implementation of inheritance:
    • Parent class, base class, super class: inherited class, Base Class, Super Class

    • Subclass, a class with inherited behavior

    • All classes must have a parent class

    • If not, the default is the word class of object

# 所有类必须有父类
# 默认为object
class Person1():
    pass

class Person2(object):
    pass

class Person():
    name = "NoName"
    age = 0
    
# 父类写在类定义的时候的括号里
class Teacher(Person):
    pass

t = Teacher()
print(t.name)
    

NoName

class Bird():
    fly = "Yes,I can"
    
    def flying(self):
        print("飞呀飞呀")
        
class BirdMan(Person, Bird):
    pass

bm = BirdMan()
bm.flying()
print(bm.name

Fly Fly
NoName

3.2 issubclass detects whether it is a subclass

  • Can be used to detect the parent-child relationship of two classes
# 利用刚才定义的Bird,BirdMan,Person,Teacher,检测父子关系

print(issubclass(BirdMan, Bird))
print(issubclass(BirdMan, Person))
print(issubclass(BirdMan, Teacher))

# help(issubclass)

True
False
False

4. Constructor

  • A function called when the function is instantiated
  • Automatic call
  • Claim:
    • The first parameter must be present, generally recommended as self
  • The call time of the constructor: It is generally considered that it is called for the first time when instantiating
  • Generally, it is not called manually, it is called automatically when instantiated, and the parameters need to be written in the brackets after the class name
class Bird():
    def __init__(self):
        print("我被调用了")
        return None
    
# 此时被调用构造函数
b = Bird()

I was called

# 构造函数2

class Person():
    def __init__(self, name, age):
        print(name, age)
        
p = Person("amy", 21)

amy 21

4.1 Inheritance of constructor

  • Constructor default inheritance
  • Once the subclass defines the constructor, the parent class constructor is no longer automatically called
# 构造函数默认继承

class Person():
    def __init__(self, name, age):
        print("Person = ({}, {})".format(name, age))
        
        
# Teacher自动继承上面的构造函数
class Teacher(Person):
    pass

t = Teacher("amy", 21)

t = Teacher()# 此代码报错

Person = (amy, 21)

Guess you like

Origin blog.csdn.net/amyniez/article/details/104363590