@property没有正确更新对象创建?

时间:2016-04-29 18:52:47

标签: python properties

我试图动态地将数据库名称添加到我的连接信息中(这是一个带有键映射值的字典,用于连接到psycopg2)。为此,我使用了一个属性。我如何想象它在我脑海中工作的原因是它将传递给对象创建者的信息,然后动态地将'database'字典中的canvas_conn属性设置为通过database_name的任何内容然后,我为@property设置了一个database_name方法,以防它被更改以更新canvas_conn。但是,我的单元测试失败了KeyError数据库'。

这是我的代码:

class Shard(mu.PrettyStr):
    def __init__(self,
                 database_name,
                 schema_name,
                 cluster_id,
                 shard_id,
                 historical_connect=False,
                 canvas_conn=config3.CANVAS_INFO,
                 analytics_conn=config3.REDSHIFT_POSTGRES_INFO_PROD):
        """

        @type database_name: str
        :param server_id:
        @type schema_name: str
        :param name:
        @type cluster_id: str
        :param cluster_id:
        @type shard_id: str
        :param shard_id:
        @type historical_connect: bool
        :param historical_connect:
        @type canvas_conn: dict
        :param canvas_conn:
        @type analytics_conn: dict
        :param analytics_conn:
        """
        self._database_name = database_name
        self.schema_name = schema_name
        self.cluster_id = cluster_id
        self.shard_id = shard_id
        self.historical_connect = historical_connect
        self._canvas_conn = canvas_conn
        self.analytics_conn = analytics_conn

    @property
    def database_name(self):
        return self._database_name

    @database_name.setter
    def database_name(self, name):
        self._database_name = name
        # force the new database name into the conn info
        self._canvas_conn = self._canvas_conn

    @property
    def canvas_conn(self):
        return self._canvas_conn

    @canvas_conn.setter
    def canvas_conn(self, database_info):
        database_info['database'] = self._database_name
        self._canvas_conn = database_info

这是我的单元测试:

def test_descriptor_correctly_sets_database_attribute(self):
        test_data = ('server_id', 'db_name', 'cluster_id', 'shard_id', True)
        test_shard = cu.Shard(*test_data)
        self.assertEqual(
            test_shard.canvas_conn['database'],
            test_shard.database_name
        )

1 个答案:

答案 0 :(得分:1)

您完全绕过了属性设置器:

self._canvas_conn = canvas_conn

直接设置_canvas_conn属性,根本不使用@canvas_conn.setter

改为设置self.canvas_conn

self.canvas_conn = canvas_conn

因为只有这样才会涉及到设置者并且设置了'database_name'键。

出于同样的原因,database setter中的以下行也没用:

self._canvas_conn = self._canvas_conn