I'm trying to figure out a way to provide multiple ways to initialize a Python class, including from another instance of the class itself. If Python supported overloading, it would be as simple as this:
class Pet:
age =0
name=""
def __init__(self, a, n):
self.age =a
self.name=n
def __init__(self, p):
self.age =p.age
self.name=p.name
This way, you could initialize a Pet object by providing the members directly or initialize it from another Pet object. Unfortunately Python doesn't support overloading, so this isn't an option.
I tried searching for a solution, but the results were either unrelated or at best, only tangentially related and skirted around this specific case—which is strange because I'd bet cash-money that I'm not the first to run into this (I was hoping the similar-questions box would find something after I typed this up, but nope).
Some of the answers to related, but different, questions I found were to use default arguments for __init__
or use isinstance
, but I'm not sure how/if those could be adapted for this.
Is there a (practical) way to accomplish this?
(Yes, I could use pet2=Pet(pet1.age, pet1.name)
, but I mean, come, on. ¬_¬ I even considered making a separate initFromClass
function, but that just makes things even messier than the previous expanded-argument solution.)