根据参数选择一个子类 [英] pick a subclass based on a parameter

查看:77
本文介绍了根据参数选择一个子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模块(db.py),它从不同的数据库类型(sqlite,mysql等)加载数据.该模块包含一个db_loader类和从其继承的子类(sqlite_loader,mysql_loader).

I have a module (db.py) which loads data from different database types (sqlite,mysql etc..) the module contains a class db_loader and subclasses (sqlite_loader,mysql_loader) which inherit from it.

使用的数据库类型在单独的params文件中,

The type of database being used is in a separate params file,

用户如何找回正确的物体?

How does the user get the right object back?

即我该怎么办

loader = db.loader()

我是在db.py模块中使用一种称为loader的方法,还是有一种更优雅的方式使类可以根据参数选择自己的子类?有没有一种标准的方法来做这种事情?

Do I use a method called loader in the db.py module or is there a more elegant way whereby a class can pick its own subclass based on a parameter? Is there a standard way to do this kind of thing?

推荐答案

听起来像您想要的工厂模式.您将参数传递给一个工厂方法(在您的模块中,或者在它可能产生的所有对象的公共父类中),它会返回正确类的实例.在python中,由于您的类型是动态的,所以这个问题比Wikipedia文章上的某些细节要简单一些.

Sounds like you want the Factory Pattern. You define a factory method (either in your module, or perhaps in a common parent class for all the objects it can produce) that you pass the parameter to, and it will return an instance of the correct class. In python the problem is a bit simpler than perhaps some of the details on the wikipedia article as your types are dynamic.

class Animal(object):

    @staticmethod
    def get_animal_which_makes_noise(noise):
        if noise == 'meow':
            return Cat()
        elif noise == 'woof':
            return Dog()

class Cat(Animal):
    ...

class Dog(Animal):
    ...

这篇关于根据参数选择一个子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆