Reclassing an instance in Python

前端 未结 8 599
野趣味
野趣味 2020-12-02 10:07

I have a class that is provided to me by an external library. I have created a subclass of this class. I also have an instance of the original class.

I now want to t

8条回答
  •  隐瞒了意图╮
    2020-12-02 10:09

    I'm not sure that the use of inheritance is best in this case (at least with regards to "reclassing"). It seems like you're on the right track, but it sounds like composition or aggregation would be best for this. Here's an example of what I'm thinking of (in untested, pseudo-esque code):

    from copy import copy
    
    # As long as none of these attributes are defined in the base class,
    # this should be safe
    class SkilledProgrammer(Programmer):
        def __init__(self, *skillsets):
            super(SkilledProgrammer, self).__init__()
            self.skillsets = set(skillsets)
    
    def teach(programmer, other_programmer):
        """If other_programmer has skillsets, append this programmer's
           skillsets.  Otherwise, create a new skillset that is a copy
           of this programmer's"""
        if hasattr(other_programmer, skillsets) and other_programmer.skillsets:
            other_programmer.skillsets.union(programmer.skillsets)
        else:
            other_programmer.skillsets = copy(programmer.skillsets)
    def has_skill(programmer, skill):
        for skillset in programmer.skillsets:
            if skill in skillset.skills
                return True
        return False
    def has_skillset(programmer, skillset):
        return skillset in programmer.skillsets
    
    
    class SkillSet(object):
        def __init__(self, *skills):
            self.skills = set(skills)
    
    C = SkillSet("malloc","free","pointer arithmetic","curly braces")
    SQL = SkillSet("SELECT", "INSERT", "DELETE", "UPDATE")
    
    Bob = SkilledProgrammer(C)
    Jill = Programmer()
    
    teach(Bob, Jill)          #teaches Jill C
    has_skill(Jill, "malloc") #should return True
    has_skillset(Jill, SQL)   #should return False
    

    You may have to read more about sets and arbitrary argument lists if you aren't familiar with them to get this example.

提交回复
热议问题