1

this is the code.

class Animal(object):
  def __init__(self):
    self.alive = "alive"
    self.good = "good"
    self.eyecolor = "varys"


sally = Animal()

sally.eyecolor = "brown"


class Canine(Animal):
    def __init__(self):
     super(Canine,self).__init__()
     self.legs = 4
     self.fur = "everywhere"
 sally = Canine()
 print(sally.eyecolor)

So in this scenario, I have a class, and an object constructed by it, sally. Now I have a new class, Canine I would like to move sally into. Is there a way I can move sally into the Canine class so she retains her original eyecolor?

  • I am aware I can just do sally.eyecolor = "brown" again, however, in the real problem I have many more attributes and doing that for each is cumbersome.

  • I was thinking copy.deepcopy(sally), but I'm not sure how I would then put her through a class instance to inherit the new class.

1 Answer 1

1

You must define a class method such as Canine.from_animal that allows to do so.

You are probably thinking of doing this because casting from one type to another is something often seen. By example, you probably did this in the past.

x = float(1) # 1.0

So why couldn't you just do this?

canine = Canine(some_animal)

The answer is that Python does not just infer how to cast a class to another, even when it is a subclass. This behaviour has to be defined by some method.

By example, if you want to cast a class object to a float, you must have defined the __float__ special method.

The natural conlusion that follows from this is that you need to implement your own class method to get an object of type Canine from an object of type Animal.

class Canine(Animal):

    ...

    @classmethod
    def from_animal(cls, animal):
        canine = cls()
        canine.eyecolor = animal.eyecolor

        # Implement any additional logic here

        return canine

sally = Animal()

sally.eyecolor = "brown"

sally = Canine.from_animal(sally) # Sally knows where she stands now

Note that there is nothing that prevents you defining the method to_canine in the class Animal instead.

class Animal(object):

    ...

    def to_canine(self):
        canine = Canine()
        canine.eyecolor = self.eyecolor
        return canine
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.