Home  >  Article  >  Backend Development  >  Detailed examples of Python's four object-oriented features

Detailed examples of Python's four object-oriented features

WBOY
WBOYforward
2022-05-26 11:58:512734browse

This article brings you relevant knowledge about python, which mainly introduces the relevant content about object-oriented. The four characteristics of object-oriented include abstraction, encapsulation, inheritance and polymorphism. Let’s take a look at it together, I hope it will be helpful to everyone.

Detailed examples of Python's four object-oriented features

Recommended learning: python video tutorial

##1. Abstract

Abstraction is the art of hiding superfluous details. In the object-oriented concept, the direct representation of abstraction is usually a class. Python basically provides all the elements of an object-oriented programming language. If you have mastered at least one object-oriented language, it will be quite easy to use Python for object-oriented programming.

Ignore the things in a topic that are not related to the current goal, and focus on the aspects related to the current goal. (It is to extract a certain type of things in the real world, express it with program code, and abstract it Generally called a class or interface).

Abstraction does not intend to understand the entire problem, but selects a part of it and does not use some details for the time being. Abstraction includes two aspects, one is data abstraction, and the other is process abstraction.

Data abstraction-->Represents the characteristics of a type of thing in the world, which are the attributes of the object. For example, a bird has wings, feathers, etc. (class attributes)

Process abstraction-->Represents the world The behavior of a type of thing is the behavior of an object. For example, a bird can fly or call (class method)

2. Encapsulation

Object-oriented programming , a class encapsulates all the required data (which can also be said to be the attributes of the class) and operations on the data (which can also be said to be the behavior of the class) in the class, which are called member variables and methods of the class ( or member function). This programming feature of encapsulating member variables and member functions is called encapsulation.

2.1 Public member variables and private member variables

In Python, the name of a member variable is used to distinguish whether it is a public member variable or a private member variable. .

In Python, variables starting with two underscores ‘_ _’ are private member variables, while the rest of the variables are public member variables.

Among them, private member variables can only be accessed inside the class, while shared public member variables can be accessed outside the class.

2.2 Public methods and private methods

The method of a class is an encapsulation of class behavior.

The methods of the class are also divided into public methods and private methods.

Private methods of a class can only be accessed inside the class through the object name (which is self within the class). Public methods can be accessed from outside the class through the object name. Similarly, public member methods and private member methods are also distinguished by their names. Methods starting with a double underscore ‘__’ are private member methods.

Private method: can only be accessed inside the class, not the object.

Private attributes: Improve code security and do not allow others to modify it at will

class Test(object):
    #私有方法
    def __test2(self):
        print("私有方法,__test2")
    #普通方法
    def test(self):
        print("普通方法test")
    #普通方法
    def _test1(self):
        print("普通方法_test1方法")
        #在类内部调用私有方法
        #t.__test2()
        self.__test2()
t = Test()
t.test()
t._test1()
#t.__test2() #调用时会报错
#Private method application scenario-sending text messages

#私有方法应用场景--发短信
class Test:
    #核心私有方法,用于发送短信
    def __sendMsg(self):
        print("---正在发送短信---")
    #公共方法
    def sendMsg(self,newMoney):
        if newMoney>10000: #余额大于10000才可以调用发短信功能
            self.__sendMsg()
        else:
            print("抱歉,余额不足,请先充值!")
t = Test()
t.sendMsg(1000000000)
#帐号不允许更改
class Person(object):
    def __init__(self,name,sex):
        self.__name = name
        self.__sex = sex
    def getSex(self):
        return self.__sex
    def getName(self):
        return self.__name
    def setName(self,newName):
        if len(newName)>=5:
            self.__name = newName
        else:
            print("名字长度必须大于等于才可修改!")
xiaoming = Person("hoongfu","男")
print(xiaoming.getName())
print(xiaoming.getSex())
xiaoming.setName("xiaoming")
print(xiaoming.getName())

2.2.1 Exercise

Define a class Person, which has private methods and common methods, private properties and common properties

Private methods can be called through ordinary methods, and private attributes can also be changed through ordinary methods.

class Test(object):
    def test(self):
        self.__sex = "保密"
        print("普通公有方法test")
        #调用私有方法
        self.__test1()
    def __test1(self):
        print("私有方法__test1")
        #调用私有属性
        print("私有属性__sex:",self.__sex)
t = Test()
t.test()
3.

Inheritance

3.1 The concept of inheritance

In the program, inheritance description is the belonging relationship between things. For example, cats and dogs are animals, and the program can be described as cats and dogs inherit from animals; similarly, Persian cats and Balinese cats both inherit from cats, while Shar-Pei and Dalmatians All inherit dogs

#Inheritance

#继承
class Animal(object):
    def eat(self):
        print("----吃----")
    def dirk(self):
        print("----喝----")
    def run(self):
        print("----跑----")
    def sleep(self):
        print("----睡觉----")
class Dog(Animal):
    '''
    def eat(self):
        print("----吃----")
    def dirk(self):
        print("----喝----")
    def run(self):
        print("----跑----")
    def sleep(self):
        print("----睡觉----")
    '''
    def call(self):
        print("旺旺叫...")
class Cat(Animal):
    def catch(self):
        print("抓老鼠....")
dog = Dog()
dog.call()
dog.eat()
tom = Cat()
tom.catch()
tom.sleep()
#Multiple inheritance

#多继承
class Animal(object):
    def eat(self):
        print("----吃----")
    def dirk(self):
        print("----喝----")
    def run(self):
        print("----跑----")
    def sleep(self):
        print("----睡觉----")
class Dog(Animal):
    def call(self):
        print("旺旺叫...")
class XiaoTq(Dog):
    def fly(self):
        print("----飞喽-------")
xtq = XiaoTq()
xtq.fly()
xtq.call()
xtq.eat()
class Cat(object):
    def __init__(self,name,color="白色"):
        self.name = name
        self.color = color
    def run(self):
        print("%s -- 在跑"%self.name)
class Bosi(Cat):
    def setName(self,newName):
        self.name = newName
    def eat(self):
        print("%s -- 在吃"%self.name)
bs = Bosi("印度猫")
print(bs.name)
print(bs.color)
bs.eat()
bs.setName("波斯猫")
bs.run()

 3.2重写父类方法与调用父类方法

所谓重写,就是子类中,有一个和父类相同名字的方法,在子类中的方法会覆盖掉父类中同名的方法.

使用super调用父类的方法:可以直接调用父类方法,不需要通过 父类名.父类方法名 的方式

class Cat(object):
    def sayHello(self,name):
        print("hello---1")
class Bosi(Cat):
    def sayHello(self):
        print("hello---2")
        #Cat.sayHello(self)
        super().sayHello("Zhangsan")
bs = Bosi()
bs.sayHello()

 3.3多继承

多继承举例:

class Base(object):
    def test(self):
        print("----Base-----")
class A(Base):
    def test(self):
        print("----test1-----")
class B(Base):
    def test(self):
        print("----test2-----")
class C(A,B):
    pass
c = C()
c.test()
print(C.__mro__) #可以查看C类的搜索方法时的先后顺序

4.多态

4.1多态的定义

所谓多态:定义时的类型和运行时的类型不一样,此时就成为多态。

多态指的是一类事物有多种形态,(一个抽象类有多个子类,因而多态的概念依赖于继承)。

当子类和父类都存在相同的print_self()方法时,我们说,子类的print_self()覆盖了父类的print_self(),在代码运行的时候,总是会调用子类的print_self()。这样,我们就获得了继承的另一个好处: 多态。

class Dog(object):
    def printSelf(self):
        print("大家好,我是xxx,请大家多多关照!")
class XiaoTq(Dog):
    def printSelf(self):
        print("Hello,ereybody,我是你们的老大,我是哮天神犬!")

#定义一个执行函数
def exec(obj):

    """

    #定义时的类型并不知道要调用哪个类的方法,

    当运行时才能确定调用哪个类的方法,这种情况,我们就叫做多态

    """

    obj.printSelf()
dog = Dog()
exec(dog)
xtq = XiaoTq()
exec(xtq)

4.2新式类和经典类的区别

新式类都从 object 继承,经典类不需要

Python 2.x中默认都是经典类,只有显式继承了object

Python 3.x中默认都是新式类,经典类被移除,不必显式的继承object

#新式类和经典类的区别

class A:
    def __init__(self):
        print('a')
class B(A):
    def __init__(self):
        A().__init__()
        print('b')
b = B()
print(type(b))
class A():
    def __init__(self):
        pass
    def save(self):
        print("This is from A")
class B(A):
    def __init__(self):
        pass
class C(A):
    def __init__(self):
        pass
    def save(self):
        print("This is from C")
class D(B,C):
    def __init__(self):
        pass
fun = D()
fun.save()

推荐学习:python视频教程

The above is the detailed content of Detailed examples of Python's four object-oriented features. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete