Custom class ideology / design

52 Views Asked by At

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.

1

There are 1 best solutions below

2
effprime On

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)