python - 实例化后从另一个类中创建一个动态类
问题描述
我需要帮助创建一个动态类,我已经阅读了许多教程和其他发布在这里的问题,但我就是不明白......这是我到目前为止所拥有的。(为了这个问题,我删除了很多不必要的行)
我正在寻找的是创建一个SpecificAsset 类,这样我就可以在购买和交易特定货币时为它们创建税收批次。此外,我想跟踪创建或销毁(出售/交易)的特定货币的数量,但我不确定该采取哪种方法。我一直更专注于尝试创建动态类。
---我目前拥有的,不起作用... -------
class AssetMeta(type):
asset_classes = {}
def __new__(cls, clsname, superclasses, attributedict):
if clsname in cls.asset_classes:
raise ValueError("Redefinition of Asset subclass '{}'".format(clsname))
tp = type.__new__(cls, clsname, superclasses, attributedict)
cls.asset_classes[clsname] = tp
return tp
# --\/--\/-- what the class should look like --\/--\/--
class SpecificAsset(metaclass=AssetMeta):
def __init__(self, owner, priAssetType, priAsset, qty, altAsset):
self.id = id(self)
self.owner = owner # an instance of a class defined in another file
self.creationDate = datetime.now()
self.priType = priAssetType # a string, either 'base' or 'quote'
self.primary = priAsset # the Currency object this asset represents
self.holdingQty = Decimal(qty) # amount of the primary asset currently held
self.initialQty = Decimal(qty) # because small portions of this asset can be sold
self.primary.holdingQty += Decimal(qty) # add qty held to the total qty of the represented asset
self.altType = 'quote' if self.priType == 'base' else 'base'
self.alternate = altAsset # the Currency object this asset is permitted to trade with
self.altValue = Decimal(0.00) # calculated when function (to be defined) is called
self.USDpointer = self.primary.pointer
self.pending = False
class Currency:
count = 0
def __init__(self, name):
Currency.count += 1
self.id = id(self)
self.name = name
self.bases = {}
self.quotes = {}
self.holdingQty = Decimal(0.00)
def point_to(self, CUR):
self.pointer = CUR
# function call within the Currency class, which is supposed to create the dynamic SpecificAsset class...
# ... also not working...
def create_asset_class(name, BaseClass=SpecificAsset):
def __init__(self, **kwargs):
for key, value in kwargs.items():
if key not in argnames:
raise TypeError("Argument %s not valid for %s"
% (key, self.__class__.__name__))
setattr(self, key, value)
BaseClass.__init__(self, name)
newclass = type(self.name,
(???,), # not sure what my parent/base class should be, or if needed
{
"__init__": __init__
})
return newclass
解决方案
推荐阅读
- rust - 当多个期货使用相同的底层套接字时,为什么我没有唤醒它们?
- c# - c# wpf确定元素是否具有在源xaml中定义的属性
- node.js - Mongoose 在数组映射中进行部分事务
- laravel - Laravel 通过电话号码进行身份验证
- c# - 边缘浏览器隐藏默认文件上传
- go - go - 如何在go中获取多部分格式文件的文件名?
- rust - 这个关于生命周期的锈函数有什么区别
- c++ - 在 C++ 中运行 system() 时收到 gnuplot 错误
- python - 如何获取每个 ObjectList、DJANGO 的总和
- python - Flask App 进行多次登录尝试的奇怪行为