自定义类意识形态/设计

问题描述

我有两个对象 profile1profile2,它们都继承自一个名为 profile 的泛型类。许多 profile2 可以与 profile1 相关,但只有 1 个 profile1 可以与 profile2 相关。在大多数情况下,它们具有相似的功能并从 profile 继承了它们的大部分行为。

我的问题是创建两个子类还是将它们全部保留为通用配置文件并包含一个可以是 profiletype12 属性会更好。子类化提出了一个挑战,因为我似乎无法弄清楚如何编写允许他们更改类型的方法

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)

如果 xprofile1y = x.changeProfileType(2) 使 y 等于 nonetype 而不是 profile2

不费心创建新对象,而是保留原始对象并在 profiletype01 之间更改 2 变量会容易得多。它只会创建一点代码膨胀,而必须检查特定行为。这也会容易得多,因为当我实现 profile 对象的集合时,通过对象更改类型会很痛苦。

但我觉得这不太符合 OOP。

解决方法

如果您的目标是只有一个 Profile 类的类型可以更改,那么您可以只拥有一个带有 setter 方法的类。我认为不需要单独的 Profile 类。如果子类具有新的或与父类不同的方法,通常您会这样做。

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)