0

I've checked a few of the stackoverflow articles, but couldn't find an answer to my question, so sorry if this is a duplicate. The closes I could find was Instantiate subclass from superclass but this still isn't exactly what I want.

So imagine I have three class: 1 super class and 2 subclasses and I want to do some weird copy method that is the same for all my classes. But in particular, my copy needs to be a new instantiation of said object. Example:

class Pet(object):
    def __init__(self,name):
        self._name = name
    def weird_copy(self):
        name = self._name + " weird"
        z = XXX(name)

class Dog(Pet):
    def __init__(self,name):
        self._name = name + " dog"

class Cat(Pet):
    def __init__(self,name):
        self._name = name + " cat"      

The XXX part is where I don't know what to do. If I do

d = Dog('ralph')
d2 = d.weird_copy()

I want d2 to be a Dog object instead of a Pet object. I tried replacing XXX with self and that started causing problems. I know there's a way to do @classmethod, but the problem with that is that I need to use properties from self, so I need to not switch "self" to "cls".

Thanks.

4
  • This is a poor design. What if one of the subclasses requires additional arguments to the constructor? Commented Jul 24, 2018 at 20:18
  • The above is a simplified version of what I actually need. If you have recommendations for a better design, I'm all ears =) Commented Jul 24, 2018 at 21:32
  • Maybe if you explained what you're really trying to accomplish. Because what you have creates poor dependencies. Commented Jul 24, 2018 at 21:41
  • In essence it's one object, but it can be represented in different ways. So what I did is made a super that handles most of the functions, but then there are subclasses that will handle particular representations of the super object. So input/output should be the same. Input should be the same for both subobjects but the output will be different. Commented Jul 24, 2018 at 23:34

1 Answer 1

2

type(self) will return a reference to the the class object of the current instance.

def weird_copy(self):
    name = self._name + " weird"
    z = type(self)(name)
    return z
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.