0

I have two objects profile1 and profile2 that both inherit from a generic class called profile. Many profile2s can relate to a profile1 but only 1 profile1 can relate to a profile2. For the most part they have similar functionality and inherit most of their behavior from profile.

My question is would it be better to create two subclasses or just keep them all as generic profiles and include a profiletype property that could be 1 or 2. Subclassing presents a challenge because I can't seem to figure out how to code a method that allows them to change their type.

def changeProfileType(self, Profiletype):
    if profiletype == 0:
        # this is the generic profile. So if 0, create a new generic profile
        # with the same name
        return Profile.__init__(self, self.name)
    elif profiletype == 1:
        #if 1, create a Profile1 with the same name
        return Profile1.__init__(self, self.name)
    elif profiletype == 2:
        #if 2, create a Profile2 with the same name
        return Profile2.__init__(self, self.name)

If x is a profile1, y = x.changeProfileType(2) makes y equal to Nonetype instead of a profile2.

It would be much easier to not bother with creating new objects and instead keep the original object and change a profiletype variable between 0, 1, and 2. It would just create a little code-bloat with having to check that with the specific behaviors. It would also be a lot easier since when I implement collections of profile objects, changing the type via objects would be a real pain.

But I feel like that's not very in keeping with OOP.

martineau
  • 119,623
  • 25
  • 170
  • 301

1 Answers1

0

If your goal is to have only one Profile class with a type that can be changed, you can just have one class with a setter method. I don't see a need for separate Profile classes. Usually you'd do this if the child classes have methods that are new or different from the parent.

class Profile:

    def __init__(self, name, pType=0):
        self.name = name
        self.type = pType

    def changeProfileType(self, pType):
        self.type = pType
profile = Profile("foo")
profile.changeProfileType(2)
effprime
  • 578
  • 3
  • 10
  • Yeah that's what I was thinking, but the required functionalities are still kind of undefined right now so it's hard to decide. Just as a point of curiosity, do you see what's wrong with my OOP approach? Why does it only return NoneType? – NoobGingrich Jan 15 '21 at 22:46
  • No offense, but it's hard to answer a question when you don't really know what you are trying to do yet :P But to answer why you are seeing None, it's because `__init__` always returns None. If you want to return a new object, I think you can use `__new__` or just call the class directly – effprime Jan 15 '21 at 22:49