1

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.)

Synetech
  • 9,643
  • 9
  • 64
  • 96
  • 1
    There are two main alternatives in that duplicate, use `def __init__(*args, **kwargs)` then parse it manually (I don't suggest this). Or, use the more idiomatic way of using a `@classmethod` and then something like `def from_pet` and you would call it like `p1 = Pet(2, 'Fido'); p2 = Pet.from_pet(p1)` – juanpa.arrivillaga Aug 15 '19 at 20:46
  • 1
    Python supports *keyword arguments*, instead of overloading. And you can always use a `@classmethod` as a factory: `@classmethod` (newline) `def from_instance(cls, instance): return cls(instance.age, instance.name)`. – Martijn Pieters Aug 15 '19 at 20:46
  • Doh! So the proper/best/pythonic solution is a mix of the two I considered and waived off? Alright, I tried it and it's not as clean as overloading, but it could certainly be worse. Thank you. (Also, the multiple-constructor question is definitely related and could have helped; I don't know why SO didn't list it in the similar-questions box. ¬_¬) – Synetech Aug 15 '19 at 21:04

0 Answers0