[Python design mode] Chapter 9th How to prepare multiple resumes-prototype mode

Source: Internet
Author: User
Tags class definition shallow copy

GitHub Address: Https://github.com/cheesezh/python_design_patterns

Topic

To design a resume class, you must have a name, you can set the gender and age, that is, personal information, you can set up the company and working hours, that is, work experience.

Base version
Class Resume (): Def __init__ (self, name): self.name = name # python default member variable exposes self.__sex = None # PYT Hon Default member variable is exposed, plus __ means private self.__age = none # python default member variable is exposed, plus __ means private Self.__time_area = none # python default member variable public, plus _ _ means private Self.__company = None # python default member variable is exposed, plus __ means private def set_personal_info (self, sex, age): Self . __sex = Sex Self.__age = Age def set_work_experience (self, Time_area, company): Self.__time_area = t Ime_area Self.__company = Company def display (self): print ("{}\t{}\t{}". Format (Self.name, self.__ Sex, Self.__age)) print ("{}\t{}". Format (Self.__time_area, Self.__company)) def main (): Resume_a = Resume ("Naruto" ) Resume_a.set_personal_info ("Male", "resume_a.set_work_experience") ("2016-2018", "Wood Leaf Company") Resume_b = Resume (" Naruto ") Resume_b.set_personal_info (" Male "," resume_b.set_work_experience ") (" 2016-2018 "," Wood Leaf Company ") Resume_c = resum E ("Naruto") resume_c.set_Personal_info ("Male", "resume_c.set_work_experience") ("2016-2018", "Wood Leaf Company") Resume_a.display () Resume_b.displa Y () Resume_c.display () main ()
鸣人  男   292016-2018   木叶公司鸣人  男   292016-2018   木叶公司鸣人  男   292016-2018   木叶公司
Comments
    • The method of generating a CV in the main function above is equivalent to a handwritten resume, and three resumes are instantiated three times.
    • And if you want to change a field, such as changing the time from one to the other, change the 2016-2018 2017-2018 same three times.

What if it's written like this?

def main():    resume_a = Resume("鸣人")    resume_a.set_personal_info("男", "29")    resume_a.set_work_experience("2016-2018", "木叶公司")        resume_b = resume_a        resume_c = resume_a        resume_a.display()    resume_b.display()    resume_c.display()    main()
鸣人  男   292016-2018   木叶公司鸣人  男   292016-2018   木叶公司鸣人  男   292016-2018   木叶公司
Comments
    • This is a reference, not a specific value, equivalent to no actual content on CV B and CV C, but rather "see CV a"
    • You can use the Clone method to solve this problem, that is, the prototype pattern
Prototype mode

Prototype mode, which specifies the kind of objects created with the prototype instance, and creates a new object [DP] by copying the prototypes. That is to create another customizable object from one object without needing to know the details of any creation.

from abc import ABCMeta, abstractmethodfrom copy import copyclass Prototype():    """    抽象原型类    """    __metaclass__ = ABCMeta    def __init__(self, id):        self.id = id            @abstractmethod    def clone(self):        passclass ConcretePrototypeOne(Prototype):    """    具体原型类    """    def __init__(self, id):        super().__init__(id)        def clone(self):        return copy(self)  # 1. 浅拷贝copy.copy() 或 深拷贝copy.deepcopy() 2. Python无需强制类型转换def main():    prototype1 = ConcretePrototypeOne("1")    prototype1_cloned = prototype1.clone()      print(prototype1_cloned.id)    main()
1
Shallow copy and deep copy in Python

When assigning values between objects in Python is passed by reference, the copy module in the standard library is required if the object needs to be copied.

    • Copy.copy (Shallow copy): Only the top-level object is copied, and the object member variables inside the top-level object are not copied;
    • Copy.deepcopy (deep copy): Copying objects and their sub-objects

Based on the basic version of the CV class definition, the type of the member variable is the basic data type (string), so a shallow copy is used. So when do you use a deep copy? If we define the work experience as a separate class workexperience, then the type of member variable in the CV class is workexperience, and if a copy operation is required, a deep copy is required.

Deep Copy prototype mode
From copy import Deepcopyclass workexperience (): Def __init__ (self, time_area= "", Company= ""): Self.time_area =  Time_area Self.company = Company Class Resume (): Def __init__ (self, name): Self.name = name #        Python default member variable exposes self.__sex = none # python default member variable is exposed, plus __ means private self.__age = none # python default member variable is exposed, plus __ means private        Self.__work_expereince = Workexperience () # python default member variable is exposed, plus __ represents private def set_personal_info (self, sex, age): Self.__sex = Sex Self.__age = Age def set_work_experience (self, Time_area, company): Self.__wor K_expereince.time_area = Time_area Self.__work_expereince.company = Company def display (self): PR Int ("{}\t{}\t{}". Format (Self.name, Self.__sex, self.__age)) print ("{}\t{}". Format (self.__work_expereince.time_ Area, Self.__work_expereince.company)) def deep_clone (self): "" "Deep Copy Method" "" Return D Eepcopy (self) def ClonE (self): "" "Shallow Copy Method" "" Return Copy (self) def main (): Resume_a = Resume ("Naruto") resume_a . Set_personal_info ("Male", "resume_a.set_work_experience") ("2016-2018", "Wood Leaf Company") Resume_b = Resume_a.clone () r Esume_b.set_work_experience ("2018-2019", "King School") Resume_c = Resume_a.clone () resume_c.set_personal_info ("Male", "24 ") resume_c.set_work_experience (" 2019-2020 "," Ask the Company ") Resume_a.display () Resume_b.display () Resume_c.displa Y () def deep_main (): Resume_a = Resume ("Naruto") resume_a.set_personal_info ("Male", "Resume_a.set_work_experienc")        E ("2016-2018", "Wood Leaf Company") Resume_b = Resume_a.deep_clone () resume_b.set_work_experience ("2018-2019", "Kings School") Resume_c = Resume_a.deep_clone () resume_c.set_personal_info ("Male", "" ") resume_c.set_work_experience (" 2019-2020 "," ask Ask the Company ") Resume_a.display () Resume_b.display () Resume_c.display () print ("---a shallow copy, the work experience has been modified to the last value---") Main () print ( "--------deep Copy, work experience for different values--------") Deep_main () 
---浅拷贝, 工作经历都被修改成最后一次的值---鸣人  男   292019-2020   问问公司鸣人  男   292019-2020   问问公司鸣人  男   242019-2020   问问公司--------深拷贝, 工作经历为不同的值--------鸣人  男   292016-2018   木叶公司鸣人  男   292018-2019   王者学校鸣人  男   242019-2020   问问公司

[Python design mode] Chapter 9th How to prepare multiple resumes-prototype mode

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.