python - 如何在不创建实例的情况下选择性地访问类方法
问题描述
我对 python 比较陌生,并且对 OOP 有所了解。我正在创建一个类来对数据执行一些基本方法,但理想情况下,我希望将这些类方法作为常规函数访问,而不必先创建实例。
我为包含单个方法“clip_sphere”的 MyMethod 设置了以下代码,该方法将 xyz 坐标作为数组接收并返回以“center”为中心、半径为“radius”的球体内的坐标
import numpy as np
class MyMethod:
def __init__(self,xyz):
self.xyz = xyz
def clip_sphere(self, center, radius):
self.xyz = self.xyz - np.array(center).reshape(1,-1)
r = (np.sum(self.xyz**2, axis = 1))**0.5
idx = r < radius
xyz_clip = self.xyz[idx,:]
self.clip = xyz_clip
return xyz_clip
我想做的是能够以两种方式运行剪辑球体,枯萎1:
C = MyMethod(xyz)
xyz_clip = C.clip_sphere(center =[0,0,0],radius = 2)
或者简单地通过调用它作为一个函数,如:
xyz_clip = clip_sphere(xyz,center =[0,0,0],radius = 2)
最好不重写为普通函数。这可能与某些装饰器有关吗?或者这甚至可能。
编辑:在浏览了一些答案之后,我想我要问的是如何获得像 numpy reshape 这样的函数。因为这通过允许以下语句起作用:
a = np.reshape(np.array([1,2,3]),[3,1])
这就像一个函数以及:
a = np.array([1,2,3])
a.reshape([3,1])
这就像一个类方法
解决方案
它是一种内置的——你需要做的就是从类的命名空间中获取函数:
C = MyMethod(xyz)
xyz_clip = MyMethod.clip_sphere(C, center =[0,0,0], radius = 2)
但是,这仍然需要您拥有该类的实例。问题在于,编写代码是为了在特定命名对象(即命名对象)中查找xyz
等属性。( Python中的名称没有什么特别之处。)self
self
如果您确实需要能够使用xyz
此功能,那么明智的方法是编写一个简单的函数来处理它:
# At top level
def clip(xyz, center, radius):
xyz -= np.array(center).reshape(1,-1)
r = (np.sum(xyz**2, axis = 1))**0.5
idx = r < radius
return xyz[idx,:]
然后为避免重复代码,您可以使用它来实现该方法:
# inside the class
def clip_sphere(self, center, radius):
# This part of the process needs to be repeated, because the
# `xyz` variable during the `clip` call is a separate name.
# However, you should consider whether you *actually* want to modify
# the object's `self.xyz` as a part of this process. My guess is you do not.
self.xyz -= np.array(center).reshape(1,-1)
self.clip = clip(self.xyz, center, radius) # uses the top-level `clip`.
推荐阅读
- encoding - 阿拉伯标签在 Geoserver 中无法正确显示
- javascript - 在 JavaScript 中等待 promise 时究竟会发生什么?
- git - 如何在不使用强制推送的情况下解决 rebase 冲突后将分支推送到远程?
- javascript - 如何在提示中添加内容并在节点程序中获取输出?
- java - 如何使用支持中断(暂停、连接丢失……)的 Spring Boot 开发获取端点?
- c - 当按位与应用于负数时会发生什么?
- asterisk - 如何限制话单文件中的通话记录数
- codenameone - 请求线程中断在 Ios 上不起作用
- apache-spark - 根据某些过滤条件比较两个数据帧的值,然后获取计数
- css - 是否可以只使用改变页面外观的 CSS 来创建按钮?