python重self_python – 在init中重新分配self

我有一个类在类体中有查找字典,我存储所有实例和一些键.

当我实例化实例时,我没有在任何变量或外部字典中保存它们,我将它们存储在这个查找字典中.

当我以某种方式实例化一个已经在dict中的实例时,我将它重新分配给dict中的那个并更新它,在其他函数中使用它的新旧值.

我想知道这是一个好习惯吗?或者我应该重构并让它有一个外部字典来保存实例.

这种行为有没有PEP指南?

例:

class MyClass:

all_instances = {} # this dictionary is in local space and it's clear that

# the only interaction is with MyClass

def __init__(self, unique_id, x, y, z):

if unique_id not in MyClass.all_instances:

self.unique_id = unique_id

self.x = x

self.y = y

self.z = z

MyClass.all_instances[unique_id] = self

else:

self = MyClass.all_instances[unique_id]

self.update(x, y, z)

def update(self, new_x, new_y, new_z):

self.x = self.do_something_with(self.x, new_x)

self.y = self.do_something_with(self.y, new_y)

self.z = self.do_something_with(self.z, new_z)

@staticmethod

def do_something_with(old_value, new_value):

# do something with old value and new and return some value

value = (old_value + new_value) / 2 # more complicated than tht

return value

while True:

for id in get_ids(): # fetch ids from some database

x, y, z = get_values(id) # fetch values from some other database

MyClass(id, x, y, z)

我得到id和值的数据库每次都在变化,所以我无法确定我是否会得到我已经实例化的数据,或者值不同.

我看到的方式是,类的所有功能都在其自身内部发生,不需要使用字典,因此不清楚它们与代码的任何其他部分的交互位置.

这是我通常会做的,没有重新分配它:

class MyClass:

def __init__(self, x, y, z):

self.x = x

self.y = y

self.z = z

def update(self, new_x, new_y, new_z):

self.x = self.do_something_with(self.x, new_x)

self.y = self.do_something_with(self.y, new_y)

self.z = self.do_something_with(self.z, new_z)

@staticmethod

def do_something_with(old_value, new_value):

# do something with old value and new and return some value

value = (old_value + new_value) / 2 # more complicated than tht

return value

all_instances = {} # this dictionary is now in global space

# and it's unclear if the only interaction is with MyClass

while True:

for id in get_ids(): # fetch ids from some database

x, y, z = get_values(id) # fetch values from some other database

if id not in all_instances:

all_instances[id] = MyClass(x, y, z)

else:

all_instances[id].update(x, y, z)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值