我想创建一个具有某些属性的对象。我想动态添加它们。与向现有对象实例添加方法类似,但使用属性而不是方法。下面是一个简单的例子。
我喜欢动态创建:
class A():
@property
def a(self):
return self._a
@a.setter
def a(self, x):
self._a = 10*x
@property
def b(self):
return self._b
@b.setter
def b(self, x):
self._b = 10*x
Run Code Online (Sandbox Code Playgroud)
要使用方法来做到这一点,我会这样做:
class B():
def __init__(self):
for i in range(70,80):
self.__dict__[chr(i)] = types.MethodType(lambda self,x: x*i, self)
Run Code Online (Sandbox Code Playgroud)
对于我尝试过的属性:
class B():
def __init__(self):
for i in range(70,80):
def tmp(self, x):
self._x = i*x
self.__dict__[chr(i)] = property(fget=lambda self: self._i, fset=tmp)
Run Code Online (Sandbox Code Playgroud)
我也找到了types.DynamicClassAttribute
,但我不确定这是否有帮助。
这里提出了一个相关问题,关于向类添加属性(在 python 2 中): Dynamically add @property in python。我不知道如何将其扩展到类的实例。
有什么方法可以从python脚本获取在inkScape中打开的当前文档的名称和路径吗?
通过inkscape扩展菜单(通过inx文件)调用该脚本。
我想选择我在运行时继承的类,无论是A类还是B类,这取决于我在AorB中的init函数的参数.我已经尝试了以下代码,但方法没有像我希望它们重载的方式重载:AorB("B").a()返回Aa()而不是Ba().如何选择我在运行时继承的类?
更新: 从下面的反应我尝试了以下代码.现在我想在C类中继承AorB,但它还没有工作:
class A(object):
def a(self):
return "I'm A.a"
def b(self):
return "I'm A.b"
class B(object):
def a(self):
return "I'm B.a"
def c(self):
return "I'm B.c"
def AorB(classname, cache={}):
if not classname in cache:
Base = globals()[classname]
class AorB(Base):
def __init__(self):
print(classname)
Base.__init__(self)
cache[classname] = AorB
return cache[classname]()
class C(AorB):
def __init__(self, classname):
AorB.__init__(classname)
if __name__ == "__main__":
a = AorB("A")
print("A.a:", a.a())
print("A.b:", a.b())
b = AorB("B")
print("B.a:", b.a())
print("B.c:", b.c())
c = C("B")
print("C.a:", c.a())
print("C.c:", c.c()) …
Run Code Online (Sandbox Code Playgroud) 我想改变
float.__str__
Run Code Online (Sandbox Code Playgroud)
float类型的构建函数(python 2)
我试图扩展这个类.
class SuperFloat(float):
def __str__(self):
return 'I am' + self.__repr__()
Run Code Online (Sandbox Code Playgroud)
但是,当我添加它时,它变成了正常的浮动
egg = SuperFloat(5)
type(egg+egg)
Run Code Online (Sandbox Code Playgroud)
返回浮动
我的最终目标也是
egg += 5
Run Code Online (Sandbox Code Playgroud)
保持超级浮动