Is it possible in Python to call a child from parent class without initialize the child?

105 Views Asked by At

I want to know if is it possible to create a parent class to handle some common logic, but have some specific logic in child classes and run it without initialize the child as it's in abstraction.

For example:

class Person:
  def __init__(self, fname, lname, country):
    self.firstname = fname
    self.lastname = lname
    self.country = country

    if country == "US":
      # Call class UnitedStates(Person)
    else if country == "CA":
      # Call class Canada(Person)

  def printCountry(self):
    print(self.firstname + " " + self.lastname + " is from " + self.country)

class UnitedStates(Person):
  def __init__(self):
    super().country="United States"
    pass

class Canada(Person):
  def __init__(self):
    super().country="Canada"
    pass

x = Person("John", "Doe", "US")
x.printCountry()

y = Person("Jane", "Doe", "CA")
y.printCountry()

So in x I have "John Doe is from United States" and in y I have "Jane Doe is from Canada".

The reason I need that come from a high complex logic and that's the easiest way to deal, so that sample is a dummy version of what I need, otherwise I'll need to find the best way for a "work around".

Thanks in advance.

0

There are 0 best solutions below