Combination, Packaging, Polymorphism

Catalog

combination

What is combination?

Composition refers to the property in one object and another object.

Why use combinations

Reducing Code Redundancy

How to use combination

Inheritance realization:

# Course Selection System: Teachers, students, teachers and students have names, ages, gender

class People:
    def __init__(self, name, age, sex, year, month, day):
        self.name = name
        self.age = age
        self.sex = sex
        self.year = year
        self.month = month
        self.day = day

    def tell_birth(self):
        print(f'''
        === Date Of Birth ===
        //Year: {self.year}
        //Month: {self.month}
        //Day: {self.day}
        ''')


class Teacher(People):
    def __init__(self, name, age, sex, year, month, day):
        super().__init__(name, age, sex, year, month, day)


class Student(People):
    def __init__(self, name, age, sex, year, month, day):
        super().__init__(name, age, sex, year, month, day)


tea1 = Teacher('tank', 18, 'male', 2001, 1, 1)
tea1.tell_birth()

Composite implementation:

class People:
    def __init__(self, name, age, sex):
        self.name = name
        self.age = age
        self.sex = sex


class Teacher(People):
    def __init__(self, name, age, sex):
        super().__init__(name, age, sex)

class Student(People):
    def __init__(self, name, age, sex):
        super().__init__(name, age, sex)


class Date:
    def __init__(self, year, month, day):
        self.year = year
        self.month = month
        self.day = day

    def tell_birth(self):
        print(f'''
        === Date Of Birth ===
        //Year: {self.year}
        //Month: {self.month}
        //Day: {self.day}
        ''')


tea1 = Teacher('tank', 18, 'male')
date_obj = Date(2001, 1, 1)
# Assign Date object to attribute date of tea1 object
tea1.date = date_obj
tea1.date.tell_birth()

Conclusion:

  • Inheritance is the relationship between classes, what is the relationship between subclasses and superclasses, and subclasses and superclasses are subordinate relationships.
  • Composition is the relationship between an object and an object. One object has another object.

Combination exercises

'''
//Course selection system needs:
    1.Student class,Teacher category, Both students and teachers have curriculum attributes., Every course is an object..
        //Course: course name, course cycle, course price

    2.Both students and teachers have the function of choosing courses., It also has the function of printing all courses..
'''


class People:
    def __init__(self, name, age, sex):
        self.name = name
        self.age = age
        self.sex = sex

    def add_course(self, course_obj):
        self.course_list.append(course_obj)

    def tell_all_course(self):
        # Get the list of courses for the current object, which holds one object after another.
        for course_obj in self.course_list:
            # The Method of Viewing Course Information for Each Course Object
            course_obj.tell_course_info()


class Teacher(People):
    def __init__(self, name, age, sex):
        super().__init__(name, age, sex)
        self.course_list = []


class Student(People):
    def __init__(self, name, age, sex):
        super().__init__(name, age, sex)
        self.course_list = []


class Course:
    def __init__(self, course_name, course_period, course_price):
        self.course_name = course_name
        self.course_period = course_period
        self.course_price = course_price

    def tell_course_info(self):
        print(f'''
        //Course Name: {self.course_name}
        //Course cycle: {self.course_period}
        //Course price: {self.course_price}
        ''')

tea1 = Teacher('tank', 18, 'male')
stu1 = Student('Xiao Ming', 18, 'male')

python_obj = Course('python', 6, 2)
linux_obj = Course('linux', 6, 1)

tea1.add_course(python_obj)
tea1.add_course(linux_obj)

tea1.tell_all_course()

encapsulation

What is encapsulation

Encapsulation refers to encapsulating a bunch of attributes into an object.

The purpose of storing data is to obtain, and the object can acquire attributes in the way of "..."

Why to encapsulate

The purpose of encapsulation is to facilitate access. Attributes can be obtained by means of object-attribute.

How to encapsulate

Features: Variables - > Data Properties

Skills: Function - > Method Properties

Within a class, define a bunch of attributes (features and skills)

Access Restriction Mechanism

What is access restriction mechanism

In class internal definitions, all data and method attributes that start with _ are hidden by python internal, so that external attributes that start with __ can not be accessed directly, such as _ name = in'

Purpose of access restriction mechanism

A bunch of privacy attributes and attributes that can not be easily accessed from outside can be hidden and can not be directly invoked from outside.

Benefits: More rigorous logic for critical data acquisition, thereby protecting data security

Privacy attributes can be processed by encapsulating an interface, doing business logic within the interface, and then returning data to the caller.

class Foo:
    # Data attribute
    __name = 'tank'

    # Method attribute
    def __run(self):
        print('running...')

    def get_name(self):
        return self.__name

    def set_name(self):
        self.__name = 'cwz'

foo = Foo()
# print(foo.__name)
foo.set_name()
print(foo.get_name())

print(foo._Foo__name)  # _ Class name _ attribute name

Note: ** In python, access to attributes is not mandatory. The attributes at the beginning of within the class are only deformed. For direct access, call the deformed name **

class Teacher:
    def __init__(self, name, age, sex):
        self.__name = name
        self.__age = age
        self.__sex = sex

    # Interface: Print User Information Interface
    def get_info(self):
        user = input('user:').strip()
        pwd = input('pwd:').strip()
        if user == 'tank' and pwd == '123':

            print(f'''
                //Name: {self. _name}
                //Age: {self. _age}
                //Gender: {self. _sex}
                ''')

    # Interface: Modifying User Information Interface
    def set_info(self, name, age, sex):
        if not isinstance(name, str):
            raise TypeError('Names must use strings')

        if not isinstance(age, int):
            raise TypeError('Age must use numbers')

        if not isinstance(sex, str):
            raise TypeError('Sex must use strings')

        self.__name = name
        self.__age = age
        self.__sex = sex

t1 = Teacher('tank', 18, 'male')
t1.get_info()
class ATM:
    # Plug-in card
    def __insert_card(self):
        print('Begin to insert cards')

    # Input password
    def __input_pwd(self):
        print('Start typing your password')

    # Input withdrawal amount
    def __input_money(self):
        print('Input withdrawal amount')

    # Began to vomit money
    def __get_money(self):
        print('Began to vomit money')

    # Print bills
    def __print_flow(self):
        print('Print bills')

    # Withdraw money interface
    def withdraw(self):
        self.__insert_card()
        self.__input_pwd()
        self.__input_money()
        self.__get_money()
        self.__print_flow()
        print('Completion of program execution')

atm = ATM()
atm.withdraw()

property

What is property?

python's built-in decorator is used primarily for methods within classes

Why use property

The purpose of using it is to change the method inside the class (def method name () into (def method))

When an object uses a method, the object. method () becomes the object.

How to use property

'''
//Calculate a person's bmi: BMI = body weight /(height * height)
'''

class People:
    def __init__(self, name, weight, height):
        self.name = name
        self.weight = weight
        self.height = height

    @property
    def bmi(self):
        return self.weight / (self.height ** 2)

p = People('cwz', 180, 1.8)
print(p.bmi)

Note: Attributes of decorated methods cannot be modified

But it can also be modified.

class People:
    def __init__(self, name, weight, height):
        self.name = name
        self.weight = weight
        self.height = height

    @property
    def bmi(self):
        return self.weight / (self.height ** 2)

    @property
    def get_name(self):
        return self.name

    # modify
    @get_name.setter
    def set_name(self, val):
        self.name = val

    # delete
    @get_name.deleter
    def del_name(self):
        del self.name


p = People('cwz', 180, 1.8)
# print(p.bmi)

p.set_name = 'nick'
# print(p.get_name)

del p.del_name

# print(p.get_name)

polymorphic

What is polymorphism

Polymorphism refers to the multiple forms of the same thing.

Purpose of polymorphism

Polymorphism is also called polymorphism. Inheritance in program is the manifestation of polymorphism.

The purpose of polymorphism is to enable multiple different types of objects to call the method names of the same name with the same functionality.

Parent Class: Define a Uniform Set of Standards

Subclasses: Following the Standard of Parent Unification

The ultimate goal of polymorphism is to unify the specification of subclass writing, so that users can call the functions of the same method more conveniently.

How to achieve:

inherit

abstract class

In python, subclasses are not required to follow a set of criteria for parent classes, so abstract classes emerge

abc module

It forces subclasses to follow a set of criteria for parent classes

import abc


class Animal(metaclass=abc.ABCMeta):
    @abc.abstractmethod
    def eat(self):
        pass

    @abc.abstractmethod
    def drink(self):
        pass

    @abc.abstractmethod
    def speak(self):
        pass


class Pig(Animal):
    def eat(self):
        pass

    def drink(self):
        pass

    def jiao(self):    # Force the use of the same criteria as the parent class, which will cause errors
        print('Hum, hum, hum...')


pig = Pig()
pig.jiao()

Duck type

If you don't know what the current target is, but you look like a duck, then you are the duck type.

In python, it is not recommended to use abstract classes to force the definition of subclasses, but the recommended subclasses follow the duck type

  • Inheritance: too high coupling, poor scalability of the program
  • Duck type: Coupling degree is the first, and the program is extensible.

Polymorphic dazzling operation

class Animal:
    def eat(self):
        pass

    def drink(self):
        pass

    def speak(self):
        pass


class Pig(Animal):
    def eat(self):
        pass

    def drink(self):
        pass

    def speak(self):
        print('Hum, hum, hum...')


class Cat(Animal):
    def eat(self):
        pass

    def drink(self):
        pass

    def speak(self):
        print('Meow meow...')


class Dog(Animal):
    def eat(self):
        pass

    def drink(self):
        pass

    def speak(self):
        print('Wang Wang Wang...')


pig = Pig()
dog = Dog()
cat = Cat()


def BARK(animal):
    animal.speak()


BARK(dog)
BARK(pig)
BARK(cat)

Tags: Python Attribute Linux

Posted on Fri, 11 Oct 2019 06:56:36 -0700 by doforumda