如何解决从字典设置类的属性
我成功地实现了一个描述符来清理我的代码,到目前为止它运行良好。此时我的代码基本上是这样的
npm ERR!
npm ERR! Found: type-fest@0.21.3
npm ERR! node_modules/type-fest
npm ERR! type-fest@"^0.21.3" from ansi-escapes@4.3.2
npm ERR! node_modules/ansi-escapes
npm ERR! ansi-escapes@"^4.2.1" from @jest/core@26.6.3
npm ERR! node_modules/@jest/core
npm ERR! @jest/core@"^26.6.0" from jest@26.6.0
npm ERR! node_modules/jest
npm ERR! peer jest@"^26.0.0" from jest-watch-typeahead@0.6.1
npm ERR! node_modules/jest-watch-typeahead
npm ERR! 1 more (react-scripts)
npm ERR! 1 more (jest-cli)
npm ERR! ansi-escapes@"^4.3.1" from jest-watch-typeahead@0.6.1
npm ERR! node_modules/jest-watch-typeahead
npm ERR! jest-watch-typeahead@"0.6.1" from react-scripts@4.0.3
npm ERR! node_modules/react-scripts
npm ERR! react-scripts@"4.0.3" from the root project
npm ERR! 2 more (jest-watcher,terminal-link)
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peerOptional type-fest@"^0.13.1" from @pmmmwh/react-refresh-webpack-plugin@0.4.3
npm ERR! node_modules/@pmmmwh/react-refresh-webpack-plugin
npm ERR! @pmmmwh/react-refresh-webpack-plugin@"0.4.3" from react-scripts@4.0.3
npm ERR! node_modules/react-scripts
npm ERR! react-scripts@"4.0.3" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict,or retry
npm ERR! this command with --force,or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See C:\Users\Khaik\AppData\Local\npm-cache\eresolve-report.txt for a full report.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Khaik\AppData\Local\npm-cache\_logs\2021-07-14T08_18_29_758Z-debug.log
PS C:\Users\Khaik\Desktop\thenewtix.vn>
然而,为了进一步减少重复,我想做这样的事情
class ABC:
att1 = Descriptor(arg1)
att2 = Descriptor(arg2)
att3 = Descriptor(arg3)
但这会导致 class ABC:
att_arg = {'att1':arg1,'att2':arg2,'att3':arg3}
for att,arg in att_arg.items():
setattr(ABC,att,Descriptor(arg))
。
已经考虑过使用包装类来执行此操作,但有没有人知道对此的优雅解决方案?
解决方法
在构造函数中怎么做?从那里你可以使用 self
对象来设置属性:
class ABC:
ATTR_ARG = {'att1':arg1,'att2':arg2,'att3':arg3}
def __init__(self):
for attr,arg in ATTR_ARG.items():
setattr(self,attr,Descriptor(arg))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。