【问题标题】:Dynamically setting class attributes which point to descriptors动态设置指向描述符的类属性
【发布时间】:2021-12-28 02:17:06
【问题描述】:

我有一个从电子表格中获取数据并将数据处理成字典的函数

def get_employee_data(path=None):
  # load excel file from 'path'
  # return processed data as dictionary
  return {
  'bob':{'id':'12039123','age':90,'occupation':'manager'}, 
  'john':{'id':'43434433','age':66,'occupation':'janitor'}, 
  'hannah':{'id':'48484839','age':1,'occupation':'proffesional hamster'},
  }

init 方法遍历字典以 set 类属性,其中“属性名称”是根据员工姓名设置的 - 我希望它存储我的描述符类, '员工'

class Employee:
  def __set_name__(self, owner, name):
    self.public_name = name
    self.private_name = '_' + name
  def __get__(self, obj, objType=None):
    print('GET...')
    return getattr(obj, self.private_name)
  def __set__(self, obj, value):
    print('SET...')
    setattr(obj, self.private_name, value)

class ManagementSystem:
  employee_data = get_employee_data()
  william = Employee() # test works as expected
  def __init__(self):
    for employee in self.employee_data:
      setattr(self, employee, Employee())
    self.william = 'william' # test works as expected

使用相同的设计,我的目标是创建另一个描述符来处理对雇员详细信息的访问,其中所述描述符将在“员工”类中分配

class EmployeeDetail:
  # example implementation:
  # ms.bob.id
  pass

为了测试,我为 ManagementSystem 'william' 创建了一个类属性,它按预期工作,但访问使用 setattr() 实例化的属性 'bob' 的行为不同

>>> ms = ManagementSystem()
SET...
>>> ms.william
GET...
'william'
>>> ms.william = 'walliamson'
SET...
>>> ms.bob
<__main__.Employee object at 0x7f7f01a54e20>
>>> ms.bob = 'bob'
>>> ms.bob
'bob'

我对为什么会出现这种情况有所了解,但无法找到解决此问题的方法。

一如既往地感谢您的帮助:)

【问题讨论】:

    标签: python python-3.x attributes descriptor python-descriptors


    【解决方案1】:

    好吧,这让我觉得很傻,但是我已经找到了解决方案,因为我已经根据这个答案回去测试了一些东西:

    Setting a class attribute with a given name in python while defining the class

    class ManagementSystem:
      employee_data = get_employee_data()
      for employee in employee_data:
        vars()[employee] = Employee()
      def __init__(self):
       for employee in self.employee_data:
         setattr(self, employee, employee)
    

    相信我之前试图在实际上是类属性之外设置属性(我正在创建实例属性):

    'william' 是一个类属性,因此存储描述符实例将处理行为 - bob 不能遵循相同的行为,并且只是 'Employee' 类的一个实例,因此当我尝试设置 bob 时,它会被覆盖

    不过,如果有更有效的方法来做到这一点(或者我的理解似乎不完整),我仍然非常感谢对我给出的答案/解释的改进,

    谢谢你:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多