Encapsulation of three characteristics of object-oriented

Keywords: Python JSON Attribute

I. inherit the json module and derive new functions

  • Inherit the JSONEncoder in the json module and derive new functions
import json
from datetime import date, datetime

#Serializable data type takes precedence in the original json module
# print(type(datetime.now()))
#<class 'datetime.datetime'>

#json cannot change the set, class

# dict1 = {
#     # 'time1': str(datetime.now())
#     'time1': datetime.now()
# }
# res = json.dumps(dict1)
# print(res)  #Object of type datetime is not JSON serializable

#Now I want to customize a class that can be json

class MyJson(json.JSONEncoder):
    #datetime.now() ---->o
    def default(self, o):
        #isinstance: judge whether an object is an instance of a class
        if isinstance(o, datetime): #True
            return datetime.strftime(o, '&Y-%m-%d %X')

        else:
            return super().default(self, o)

dict1 = {
    'time1': datetime.now(),
    'name': 'yafeng'
}

#Specify a custom MyJson derived class
#cls = custom class
res = json.dumps(dict1, cls=MyJson)
print(res)
#{"time1": "&Y-11-27 14:32:22", "name": "yafeng"}

Two, combination

  • Three questions about life
'''
Three deadly questions:
    1. What is a combination?
        A combination is an object that contains one or more objects
    2. Why use combination?
        Reduce code redundancy
    3. How to use combination?

Coupling degree:
    Lotus root: lotus root
    -Higher coupling: lower program scalability
    -Lower coupling: higher program scalability

Conclusion:
    - inheritance:
        Inheritance is the relationship between classes. Subclasses inherit the properties and methods of their parents. Subclasses and their parents are a kind of 'subordinate' relationship
    - combination:
        Composition is the relationship between an object and an object. An object has properties / methods in another object. It is a relationship between what and what

'''
  • Examples implemented by combination
# #inherit
# #Parent class
# 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}
#
#         ''')
#
#
# #Teacher category
# class Teacher(People):
#     def __init__(self, name, age, sex, year, month, day):
#         super().__init__(name, age, sex, year, month, day)
#
# #Student class
# 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, 11)
# stu1 = Student('yafeng', 16, 'male', 2003, 12, 11)
#
# print(tea1.name, tea1.age, tea1.sex, tea1.year, tea1.month, tea1.day)
# tea1.tell_birth()
#
# '''
# tank 18 male 2001 1 11
#
#         =====Date of birth=====
#             Year: 2001
#             Month: 1
#             Day: 11
# '''
# print(stu1.name, stu1.age, stu1.sex, stu1.year, stu1.month, stu1.day)
# stu1.tell_birth()
# '''
# yafeng 16 male 2003 12 11
#
#         =====Date of birth=====
#             Year: 2003
#             Month: 12
#             Day: 11
#
# '''


#Using combination to realize
class People:
    def __init__(self, name, age, sex):
        self.name = name
        self.age = age
        self.sex = sex

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

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

#Date class
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', 25, 'female')
date_obj = Date('1994', 1, 11)
#The teacher object contains a custom date object
tea1.date_obj = date_obj
tea1.date_obj.tell_birth()
'''
        =====Date Of Birth =====
            //Year: 1994
            //Month: 1
            //Day: 11
        
'''

stu1 = Student('yafeng', 18, 'male')
date_obj = Date('1196', 1, 30)

stu1.date_obj = date_obj
stu1.date_obj.tell_birth()
'''
        =====Date Of Birth =====
            //Year: 1196
            //Month: 1
            //Day: 30
        
'''
  • Combination exercises
'''
//Practice needs:
    //Course selection system:
        1,Students, teachers, students and teachers have attributes'Name, age, gender, course'
        2,There are ways for teachers and students to add courses and print learning/Courses taught
        #Implemented in combination
'''


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

    # Print date of birth
    def tell_birth(self):
        # pass
        print(f'''
        //Year: {self. Date ﹐ obj. Year} ﹐ after stu1. Date ﹐ obj = date ﹐ obj
        //Month: {self. Date {obj. Month}
        //Day: {self. Date {obj. Day}
        ''')

    # Add courses
    def add_course(self, course_obj):
        self.course_list.append(course_obj)

        # pass

    # Print all course information in the current schedule
    def tell_all_course(self):
        # Remove all course objects from the current object course list
        for couser_obj in self.course_list:
            couser_obj.tell_course_info()

class Student(People):
    def __init__(self, name, age, sex):
        super().__init__(name, age, sex)
        # Student's own course list
        self.course_list = []


class Teacher(People):
    def __init__(self, name, age, sex):
        super().__init__(name, age, sex)
        # Teacher's own course list
        self.course_list = []


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


# Define a course class: courses include: course name, course price, course cycle
class Course:
    def __init__(self, course_name, course_price, course_time):
        self.course_name = course_name
        self.course_price = course_price
        self.course_time = course_time

        # Define printing course method: print only one course information

    def tell_course_info(self):
        print(f'''
        =====The course information is as follows=====
            //Course Name: {self. Course {name}
            //Course price: {self. Course {price}
            //Course time: {self. Course {time}
        ''')


# Create student object
stu1 = Student('yafeng', 18, 'male')
date_obj = Date(2001, 1, 30)
stu1.date_obj = date_obj

# Create course object
python_obj = Course('python', 66666, 6)
go_obj = Course('go', 29998, 5)

# Add course object to current student object
# Add python course
stu1.add_course(python_obj)

# Add go course
stu1.add_course(go_obj)

# Current student prints all course information
stu1.tell_all_course()

Three, encapsulation

  • Package introduction
'''
Three questions about life
    1. What is encapsulation?
        Seal: like a bag, seal it
        Pack: for example, pack a bunch of kittens and puppies in a bag
        #Object ----- > is equivalent to a bag
        Encapsulation refers to a collection of properties and methods that can be put together. Encapsulate into objects

        ps: an object is like a "bag / container", which can store a bunch of properties and methods
        ps: save is not the purpose. The purpose is to get. You can get the property or method by the way of object

    2. Why to package?
        Attribute or method can be 'stored / obtained' by 'object.'
        Object has a mechanism for '.'
        Convenient data access

    3. How to package?
        class user:
            x = 10
            def func():
                pass

            obj = user()
            obj.y = 20
            obj ---->x,func,y

'''

IV. access restriction mechanism

  • Access restriction mechanism
'''
//Three deadly questions:
    1,What is access restriction mechanism?
        //For properties or methods defined within a class,
        //Property or method names that begin with \\\
        ps: Looks like hiding the property or method

        #python specific
        //Note: any property or method that begins with "is defined inside the class, it will be transformed into" class name "property / method.

    2,Why are there access restrictions?
        //For example, some private data should be hidden so that it is not easily accessible to the outside

        -Interface:
            //It can encapsulate data into an interface, which can be called by users,
            //And through the corresponding logic, finally return the data to the user

    3,How to achieve it?


'''


# # demo1
# class User:
#
#     #__Properties at the beginning
#     __name = 'yafeng'   #__The name is changed to a class name
#
#     #__Method at the beginning
#     def __run(self):
#         print('yafeng is running')
#
#
# # print(User.__name)  #AttributeError: type object 'User' has no attribute '__name'
# #No direct access
#
# obj = User()
# print(obj._User__name)  #yafeng


# #demo2
# class User:
#     #__Properties at the beginning
#     __name = 'yafeng'
#     __age = 18
#     __sex = 'male'
#     __ID = '12345678966'
#     __bal = 12345678910
#
#     def __init__(self, name, age, sex):
#         self.__naem = name
#         self.__age = age
#         self.__sex = sex
#
#
#     #Verify the interface to obtain user information
#     def parse_user(self, username, password):
#         if username == 'yafeng_handsome' and password == '666':
#             print(f'''
#             Get user information through authentication
#             User name: {self. 「 naem}
#             User age: {self. 「 age}
#             User gender: {self. 「 sex}
#             User ID: {self. 「 ID}
#             User assets: {self. 「 BAL}
#             ''')
#         else:
#             print('verification failed, unable to query user information! )
#
#     #__Method at the beginning
#     def __run(self):
#         print('yafeng is running...')
#
# obj = User('yafeng', 18, 'male')
# obj.parse_user('yafeng_handsome', '666')
# '''
#             Get user information through authentication
#             User name: yafeng
#             User age: 18
#             User gender: male
#             User ID:12345678966
#             User assets: 12345678910
# '''
#

#demo3
class ATM:
    #Withdrawal function
    #1. Insert bank card
    def __insert_card(self):
        print('Begin to insert cards...')
        pass

    #2. Enter password
    def __input_pwd(self):
        print('Input password...')
        pass

    #3. Input withdrawal amount
    def __input_bal(self):
        print('Enter withdrawal amount...')
        pass

    #4, pay
    def __output_money(self):
        print('Began to vomit money...')
        pass

    #5. Print daily statement
    def __print_flow(self):
        print('Print daily statement...')
        pass

    #Withdrawal sequence interface
    def withdraw(self):
        #1. Insert bank card
        self.__insert_card()

        #2. Enter password
        self.__input_pwd()

        #3. Input withdrawal amount
        self.__input_bal()

        #4, pay
        self.__output_money()

        #5. Print daily statement
        self.__print_flow()

atm_obj = ATM()
atm_obj.withdraw()

V. proptry

  • Application of property
'''
Three deadly questions:
    1. What is property?
        Is a python built-in decorator that can be decorated on 'methods inside a class'.
        This method can be called by object. Method () --- > object. Method

    2. Why use property?
        ps: in some scenarios, the called method is only used to get a calculated value
        ps: must be called through object. Method () to make the method look like a verb

        Make the method of noun more reasonable when calling
        The purpose is to confuse the caller and mistake the called method for an attribute

    3. How to use it?
'''


#Demand: calculate BMI
 #Formula: BMI = weight / height square
#value = weight/(height*height)
class User:
    def __init__(self, name, height, weight):
        self.__name = name
        self.weight = weight
        self.height = height

    #How to get BMI index
    @property
    def BMI(self):

        return self.weight/(self.height**2)

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

    @name.setter
    def name(self, value):
        self.__name = value

    @name.deleter
    def name(self): delete attribute
        del self.__name






user_obj = User('yafaneg', 1.77, 64)

# user_obj.BMI()
# print(user_obj.BMI())
#20.428357113217785


#@After property
print(user_obj.BMI)
#20.428357113217785
 #Note that you cannot add () after BMI at this time, otherwise an error will be reported

# print(user_obj.BMI())
#TypeError: 'float' object is not callable

# print(user_obj.name)  #yafaneg
#
#
#Modify properties
 #user_obj.name = 'sub peak'
#Print (user obj. Name)


#Delete attribute
del user_obj.name
print(user_obj.name)  #AttributeError: 'User' object has no attribute '_User__name'

Posted by srdva59 on Wed, 27 Nov 2019 03:53:55 -0800