Python Basics - inheritance, polymorphism

1, slots

  • __ slots__ Property corresponds to a tuple type value
  • Specify the attributes that can be used by the object. Only the values that appear in the tuple can be set to the object
class Person(object):

    __slots__ = ('name', 'age') # Want a Yuanzu ()

    def __init__(self, name, age):
        self.name = name
        self.age = age

p = Person('zhangsan', 18)  # Object P, with name and age attributes
p.addr = 'Shanghai'

# An error will be reported AttributeError: 'Person' object has no attribute 'addr'. To avoid an error, you need to add addr to the slots parameter
# If not__ slots__ Method, no error will be reported, because python supports dynamic types, and adding attributes is OK

2, Private properties and private methods

  • 1. Private attribute: add two underscores (self. _money). This attribute is called private attribute and can only be accessed internally, not externally
  • Use internal methods to access and return the private property return self__ money
  • Print (P. _person_money) can use the object name_ Class name__ Private property name to force access to private properties. This method is not recommended
  • 2. Private method: private method usage__ Start by defining the private method__ The demo is only for internal use and cannot be accessed externally
  • p._Person__demo() can be by object name_ Class name__ Private method names enforce access, which is not recommended
import time

class Person(object):
    def __init__(self, name, age, money):
        self.name = name
        self.age = age
        # Add two underscores. This property is called private property and can only be accessed internally, not externally
        self.__money = money

    def get_money(self):  # money can be accessed internally, and then the method can be called externally as an interface (connecting internal and external)
        print('{}Check the balance!!!!'.format(time.asctime()))  # Query balance time
        return self.__money

    def set_money(self, money):
        print('The balance has been modified!!!')
        self.__money = money

    def test(self):
        self.__demo()
        print('Encrypted code 1')
        print('Encrypted code 2')
        print('Encrypted code 3')
        print('Encrypted code 4')
        print('Encrypted code 5')
        print('I am person Inside test function')

    def foo(self):  # Defined private method__ demo for internal use only
        self.__demo()

    # Private method usage__ start
    def __demo(self):
        print('Encryption step 1')
        print('Encryption step 2')
        print('Encryption step 3')
        print('Encryption step 4')
        print('Encryption step 5')
        print('Encryption step 6')
        print('Encryption step 7')


p = Person('zhangsan', 18, 2000)
p.test()
print(p.get_money())

# p.__demo() is a private method and cannot be accessed externally
# p._Person__demo() can be by object name_ Class name__ The private property name is mandatory and is not recommended

p.set_money(1500)
print(p.get_money())

# If you want to access private properties, you can use the object name_ Class name__ Private property name to enforce access
# print(p._Person__money)   # This approach to accessing private properties is strongly discouraged

# Private property__ money cannot be accessed directly from outside
# print(p.__money)
# p.__money -= 500
# print(p.__money)

3, Inherit

1. Private property, private method

  • Private attributes are not inherited by subclasses;
  • Private methods are not inherited by subclasses;
  • The Student class inherits from the Person class, so you can use the methods in the Person class;
  • s objects can also call methods of their own classes
class Person(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age
        self.money = 1000
        self.__xxx = 'hello'  # Private property

    def eat(self):
        print(self.name + 'I am eating')

    def sleep(self):
        print(self.name + 'be sleeping')

    def __foo(self):
        print('fooooooooooooooooooooooooooo')


class Student(Person):
    # def __init__(self, name, age, school):
    #     self.name = name
    #     self.age = age
    #     self.school = school

    def study(self):
        # The private property of print (self. _xxx) is not inherited by subclasses
        # self.__foo() private methods are not inherited by subclasses
        print(self.name + 'I am learning')


# s = Student('zhangsan', 18,' spring flower kindergarten ')
s = Student('zhangsan', 18)
print(s.money)  # 1000

# The Student class inherits from the Person class, so you can use the methods in the Person class
s.eat()

# s objects can also call methods of their own classes
s.study()

2. Characteristics of inheritance (multi-level inheritance)

Parent class (base class), child class (derived class)

  • When an object's property or method is called, the__ mro__ Property. If it is found, it will be stopped directly; If you don't find it in the end, report an error!!!
class Animal(object):
    def eat(self):
        print('Animals are eating')

    def sleep(self):
        print('The animal is sleeping')

    def demo(self):
        print('I am animal Inside demo method')


class Person(Animal):
    def drive(self):
        print('People are driving')

    def make_money(self):
        print('Made a little money')


class Dog(Animal):
    def bark(self):
        print('The dog is barking')


class RichPeople(Animal):
    def make_money(self):
        print('The rich made a lot of money')


class Boss(object):
    def offer(self):
        print('The boss gave you the company')

    def demo(self):
        print('I am boss Inside demo method')


class Student(RichPeople, Person, Boss):  # Multiple inheritance
    def study(self):
        print('The students are studying')


class Teacher(Person):
    def teach(self):
        print('The teacher is in class')


s = Student()  # Instantiate an object s
s.study()
s.drive()
s.eat()
s.make_money()
s.offer()
s.demo()  # I am the demo method in animal, which will be called in the order of the parent class
s.xxx()  # An error will be reported because none of the parent classes have this method

# (<class '__main__.Student'>, <class '__main__.RichPeople'>, <class '__main__.Person'>, <class '__main__.Animal'>, <class '__main__.Boss'>, <class 'object'>)
# When an object's property or method is called, the__ mro__  Property. If it is found, it will be stopped directly; If you don't find it in the end, report an error!!!
print(Student.__mro__)

3. New and classic

New class: the class inherited from object is a new class
Classic class: there is no class inherited from object
After Python 3, if you create a class without specifying a parent class, it inherits from object by default. Python 3 has no classic class


class Person(object):
    def test(self):
        print('hello')

p = Person()
p.test()
print(Person.__mro__)  # (<class '__main__.Person'>, <class 'object'>)

4, Method override

  • The subclass extends its functions on the basis of the parent class: parent class name. Function name (parameter). In this case, you need to pass the parameter self
  • That is, before calling the subclass test method, first call the test method of the parent class, that is, the subclass extends the method of the parent class, first call the method of the parent class, and then implement the subclass
  • super(). Function name ()
class Person(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age
        self.money = 1000

    def test(self):
        print(self.name + ' say hello')

class Student(Person):
    def __init__(self, name, age, school):
        # Subclasses extend their functions on the basis of parent classes
        # Parent class name. Function name (parameter)
        # Person.__init__(self, name, age)

        # super(). Function name ()
        super().__init__(name, age)
        self.school = school

    def study(self):
        print('The students are studying')

    def test(self):
        # Person.test(self)  # 
        super().test()  # Before calling the subclass test method, first call the test method of the parent class, that is, the subclass extends the method of the parent class, first call the method of the parent class, and then implement the subclass
        print('hehe')


s = Student('zhangsan', 18, 'Chuntian Huahua kindergarten')
print(s.money)
s.test()  # zhangsan say hello hehe first calls the test method of the parent class, and then calls the test method of the subclass.
# s.study()

5, Polymorphism

Polymorphism: when different subclass objects call the same parent method, the results may be different

#  1. When polymorphism is not used

class SearchDog(object):
    def sd_work(self):
        print('Search and rescue dogs are searching for life')

class PoliceDog(object):
    def pd_work(self):
        print('The police dog is catching the bad guys')

class FlyDog(object):
    def fd_work(self):
        print('The flying dog is flying')

class Person(object):
    def __init__(self, dog=None):
        self.dog = dog

    def work_with_sd(self):
        self.dog.sd_work()

    def work_with_pd(self):
        self.dog.pd_work()

    def work_with_fd(self):
        self.dog.fd_work()


p = Person()

sd = SearchDog()
pd = PoliceDog()
fd = FlyDog()

p.dog = sd  # If you change a dog, you have to change the corresponding method
p.work_with_sd()

#  2. When using polymorphism
class Dog(object):
    def dog_work(self):
        print('The dog is working')

# All inherit the Dog class
class SearchDog(Dog):
    def dog_work(self):  # Override Dog method
        print('Search and rescue dogs are searching for life')


class PoliceDog(Dog):
    def dog_work(self):
        print('The police dog is catching the bad guys')


class FlyDog(Dog):
    def dog_work(self):
        print('The flying dog is flying')


class BlindDog(Dog):
    def dog_work(self):
        print('The guide dog is leading the way')


class Person(object):
    def __init__(self, dog=None):
        self.dog = dog

    def work_with_dog(self):
        self.dog.dog_work()  # self.dog find guide dog, then call dog_. Work () method, and BlindDog() overrides this method


sd = SearchDog()
pd = PoliceDog()
fd = FlyDog()
bd = BlindDog()

p = Person(bd)  # Pass bd in, that is, BlindDog guide dog. If you call other, you can pass in the parameters
p.work_with_dog()  # The guide dog is leading the way

Keywords: Python

Added by caramba on Thu, 07 Oct 2021 18:17:24 +0300