首页 > 解决方案 > 如何在不创建实例的情况下选择性地访问类方法

问题描述

我对 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])

这就像一个类方法

标签: pythonclassinstance

解决方案


它是一种内置的——你需要做的就是从类的命名空间中获取函数:

C = MyMethod(xyz)
xyz_clip = MyMethod.clip_sphere(C, center =[0,0,0], radius = 2)

但是,这仍然需要您拥有该类的实例。问题在于,编写代码是为了在特定命名对象(即命名对象)中查找xyz等属性。( Python中的名称没有什么特别之处。)selfself

如果您确实需要能够使用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`.

推荐阅读