我将在C模块中定义的类型作为子类,以别名某些属性和方法,以便我的脚本在不同的上下文中工作。
为了使它起作用,我必须手动调整班级字典吗?如果我没有在字典中添加对DistanceTo
的引用,则会得到Point3d has no attribute named DistanceTo
。
class Point3d(App.Base.Vector):
def __new__(cls, x, y, z):
obj = super(Point3d, cls).__new__(cls)
obj.x, obj.y, obj.z = x, y, z
obj.__dict__.update({
'X':property(lambda self: self.x),
'Y':property(lambda self: self.y),
'Z':property(lambda self: self.z),
'DistanceTo':lambda self, p: self.distanceToPoint(p)})
return obj
def DistanceTo(self, p): return self.distanceToPoint(p)
我在想,一旦__new__
返回一个实例,我仍然可以用方法和属性来填充它。谁能对此有所启发?
编辑:我从中导入的模块是FreeCAD。 C基本类型定义为there。然后从此定义派生Vector here
EDIT2:我也尝试了以下方法:
class Point3d(App.Base.Vector):
def __new__(cls, x, y, z):
obj = super(Point3d, cls).__new__(cls)
obj.x, obj.y, obj.z = x, y, z
obj.__dict__.update({
'X': x, 'Y': y, 'Z': z,
'DistanceTo':lambda self, p: self.distanceToPoint(p)})
return obj
def DistanceTo(self, p): return self.distanceToPoint(p)
创建第二个点后,无论实例创建时传递了什么p
参数,Point3d p.X
都将返回p.Y
,p.Z
和x,y,z
的最后一个点的值。 p.x, p.y, p.z
返回期望值。似乎表明字典是在实例之间共享的。
编辑3:问题解决了! Py_TPFLAGS_BASETYPE位设置为零,以防止子类化,如下面的答案所述。
参考方案
我不明白为什么要动态添加属性。只需使用:
class Point3d(App.Base.Vector):
def __init__(self, x, y, z):
super().__init__(x, y, z) # or maybe super().__init__([x, y, z])
@property
def X(self):
return self[0] # guessing that App.Base.Vector works like a list
@property.setter
def X(self, value):
self[0] = value
# Y and Z likewise.
在返回'Response'(Python)中传递多个参数 - python我在Angular工作,正在使用Http请求和响应。是否可以在“响应”中发送多个参数。角度文件:this.http.get("api/agent/applicationaware").subscribe((data:any)... python文件:def get(request): ... return Response(seriali…
R'relaimpo'软件包的Python端口 - python我需要计算Lindeman-Merenda-Gold(LMG)分数,以进行回归分析。我发现R语言的relaimpo包下有该文件。不幸的是,我对R没有任何经验。我检查了互联网,但找不到。这个程序包有python端口吗?如果不存在,是否可以通过python使用该包? python参考方案 最近,我遇到了pingouin库。
如何用'-'解析字符串到节点js本地脚本? - python我正在使用本地节点js脚本来处理字符串。我陷入了将'-'字符串解析为本地节点js脚本的问题。render.js:#! /usr/bin/env -S node -r esm let argv = require('yargs') .usage('$0 [string]') .argv; console.log(argv…
Python:传递记录器是个好主意吗? - python我的Web服务器的API日志如下:started started succeeded failed 那是同时收到的两个请求。很难说哪一个成功或失败。为了彼此分离请求,我为每个请求创建了一个随机数,并将其用作记录器的名称logger = logging.getLogger(random_number) 日志变成[111] started [222] start…
Python-Excel导出 - python我有以下代码:import pandas as pd import requests from bs4 import BeautifulSoup res = requests.get("https://www.bankier.pl/gielda/notowania/akcje") soup = BeautifulSoup(res.cont…