开发者

OOP: What would be the best way to design this object?

I have a settings object that contains some generic settings. These settings will change for each user. I'm wondering what would be the best way to code this. My current method is this:

class Settings(object):

    def __init__(self, user=None):

        if user and not isinstance(user, users.User):
            raise TypeError('must be a User object')

        self.user = user

    @property
    def title(self):

        if self.user:
            return 'user setting'

        return 'generic setting'

Given that there will be a few methods in Settings, having to run that if statement each time kinda sucks.

I was considering having a UserSettings class that extends Settings to override the defaults and provide the user specific settings. Though, I've heard that overriding methods is bad OOP design. Which leads me to option 2...

I then thought of creating UserSettings but it won't extend Settings. It'll instead wrap it and I'll have something like:

class UserSettings(object):

    def __init__(self, user=No开发者_运维问答ne):

        if user and not isinstance(user, users.User):
            raise TypeError('must be a User object')

        self.user     = user
        self.settings = Settings()

    @property
    def title(self):

        return 'user setting'

So I can then do:

print user_settings.title # get the user title
print user_settings.settings.title # get the generic title

How should I code this?


Overriding methods is not only not bad OOP design, it's the basis for subtype polymorphism, which is core to OOP, and a common way to get rid of the need for such conditional checks.

There are certainly times when you should prefer composition to inheritance, but it's not clear from your description that there's anything wrong with making this a subclass.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜