在Python类构造函数中指定参数的默认值而不写继承有什么简单的方法吗?

2024-06-01 22:42:02 发布

您现在位置:Python中文网/ 问答频道 /正文

在旧类的基础上设置一些旧类的默认参数值,有没有容易得到的新类?代码如下:

class DB():
    def __init__(self, ip, port, dbname, table):
        self.ip = ip
        self.port = port
        self.dbname = dbname
        self.table = table

    def process(self):
        print self.ip, self.port, self.dbname, self.table

现在,我需要获得一组新类,这些类的默认值为OldClass.aOldClass.bOldClass.c,我将执行以下操作:

class UserDB(DB):
    def __init__(self, dbname, table):
        OldClass.__init__(self, ip='user.db.com', port='1234', dbname=dbname, table=table)

class ProdDB(DB):
    def __init__(self, dbname, table):
        OldClass.__init__(self, ip='prod.db.com', port='1314', dbname=dbname, table=table)

class CommentDB(DB):
    def __init__(self, dbname, table):
        OldClass.__init__(self, ip='comment.db.com', port='1024', dbname=dbname, table=table)

class MeetingDB(DB):
    def __init__(self, dbname, table):
        OldClass.__init__(self, ip='meeting.db.com', port='8888', dbname=dbname, table=table)

userDB = UserDB('user', 'new')
userDB.process()
prodDB = ProdDB('prod', 'lala')
prodDB.process()
commentDB = UserDB('comm', 'gg')
commentDB.process()
meetingDB = MeetingDB('met', 'ok')
meetingDB.process()

我记得有一些技巧可以简化这些子类详细代码。欢迎任何建议。提前谢谢。你知道吗


Tags: selfipcomdbinitportdeftable
3条回答

你可以用另一种间接方法来解决任何问题 在MyDB之间有另一个类怎么样?地址:

from __future__ import print_function  # for legacy Python


class DB():
    def __init__(self, ip, port, dbname, table):
        self.ip = ip
        self.port = port
        self.dbname = dbname
        self.table = table

    def process(self):
        print(self.ip, self.port, self.dbname, self.table)

添加覆盖__init__()的类:

class MyDB(DB):
    def __init__(self, dbname, table):
        super(MyDB, self).__init__(self.ip, self.port, dbname, table)

现在与类属性一起使用。这些类不再需要__init__()

class UserDB(MyDB):
    ip = 'user.db.com'
    port = '1234'

class ProdDB(MyDB):
    ip = 'prod.db.com'
    port = '1314'

制作两个测试实例:

user_db = UserDB('user', 'new')
user_db.process()

prod_db = ProdDB('prod', 'lala')
prod_db.process()

输出:

user.db.com 1234 user new
prod.db.com 1314 prod lala

这提供了一种相当声明性的做事方式。 它应该非常可读,特别是当类UserDBProdDB没有方法时。你知道吗

由于实例self.ipself.port,中不存在self,如果我们使用UserDB,搜索将继续到当前类的类属性,即UserDB。你知道吗

您不需要调用父类__init__,因为您只需要设置实例属性的值。您只需执行以下操作:

class DB():
    def __init__(self, dbname, table):
        self.dbname = dbname
        self.table = table
        self.ip = 'user.db.com'
        self.port = '1234'

我觉得干净多了。事实上,你不需要4个儿童班。您可以在单个类中使用参数来区分每个数据库的类别,如下所示:

class DB():

    # Database type configuration
    db_type_conf = {
        'user': {
            'ip': 'xx.xx.xx',
            'port': 'xxxx',
        },
        'comment': {
            'ip': 'xx.xx.xx',
            'port': 'xxxx',
        },
        'prod': {
            'ip': 'xx.xx.xx',
            'port': 'xxxx',
        },
        'meeting': {
            'ip': 'xx.xx.xx',
            'port': 'xxxx',
        }
    }

    def __init__(self, db_type, dbname, table):
        self.dbname = dbname
        self.table = table
        self.port, self.ip = self._get_port_and_ip_from_db_type(db_type)
        #                    return port and ip based on `db_type` ^

    @staticmethod
    def _get_port_and_ip_from_db_type(db_type):
       db_type_conf = self.__class__.db_type_conf[db_type]
       return db_type_conf['port'], db_type_conf['ip']

    def process(self):
        print self.ip, self.port, self.dbname, self.table

要创建对象,只需执行以下操作:

user_db = DB('user', 'user', 'new')
user_db.process()

继承是一件了不起的事情:

class DB():
    def __init__(self, ip, port, dbname, table):
        self.ip = ip
        self.port = port
        self.dbname = dbname
        self.table = table

    def process(self):
        print self.ip, self.port, self.dbname, self.table


class UserDB(DB):
    def child_func(self):
        print "We Dont share Email Ids :)"

a = UserDB("151.101.1.69", 1999, "UsersInfo", "user_log")
a.process()
a.child_func()


b = UserDB("151.101.1.69", 2001, "ClickInfo", "click_log")
b.process()
b.child_func()

相关问题 更多 >