instancemethod装饰器在哪里?

| 在我的代码中,我有一个返回类实例的方法,如下所示:
class MyClass:
  def fun( self, *args ): # the method
    return Props( self, *args )

class Props: # the returned object
  def __init__( self, parent, *args ):
    self.parent = parent
    self.args = args
为了使事情井井有条,我正在考虑将道具放置在MyClass内。然后,我想绕开乐趣,直接将类设为MyClass的实例方法,如下所示:
class MyClass:
  @instancemethod # does not exist!
  class fun:
    def __init__( self, parent, *args ):
      self.parent = parent
      self.args = args
请注意注释-instancemethod装饰器不存在。 有没有办法做到这一点,即将可调用对象变成实例方法?如果我将@instancemethod更改为@classmethod,则构造工作正常,除非父类当然是类,而不是实例。令我感到惊讶的是,我似乎找不到与之相反的操作。 好奇将其清除! 编辑: 看来我的问题不清楚。我所拥有的是一个有趣的成员函数,它不返回单个值或元组,而是返回一个充满数据的对象。该数据是基于MyClass对象和函数参数的内容生成的。我的初始代码正是我想要的。第二个代码是我希望编写它的方式。 此外,我注意到我正在寻找的装饰器只是以下内容:
def instancemethod( cls ):
  def f( *args ):
    return cls( *args )
  return f
当然,它与我打算绕过的“有趣”方法相同。还要注意的是,琐碎的“ return cls”并不完全相同,即使乍一看也是如此。 使用此装饰器,我的第二个类定义有效并产生了所需的结果,即a.fun()返回基于(可能)基于a中的数据初始化的对象:
a = MyClass()
p = a.fun(1,2,3)

print a        # <__main__.MyClass instance at 0xb775b84c>
print p.parent # <__main__.MyClass instance at 0xb775b84c>
print p.args   # (1, 2, 3)
如果这里定义的instancemethod不能作为python内置函数使用,这仍然给我一个问题,因为在classmethod和staticmethod旁边似乎没有什么地方。但是,如果没有,我想我可以忍受这种结构。     
已邀请:
我不确定您要做什么,但是我怀疑您想阅读描述符。 基本上,描述符是一个类的属性,该类本身就是定义
__get__
__set__
方法的类。在您的情况下,您可以将代码从
Props.__init__
移到
Props.__set__
,将
Props
设置为类的
fun
属性,所有代码都应按需要工作。     
我认为您无缘无故地使事情复杂化;也许您已经习惯了其他语言,并希望从那里继承自己的习惯。 IIUC,您打算执行以下操作:
class SomeClass:
    # typical stuff
    def __init__(self, other, arg1, arg2, arg3, arg4):
        self.parent= other
        # blah blah

class SomeOtherClass:
    # initialize in __init__, setup stuff
    def __init__(self, initarg1, initarg2):
        self.initarg1= initarg1
        self.initarg2= initarg2

    def fun(self, arg3, arg4):
        # return an instance of SomeClass based on
        # initargs and arguments
        return SomeClass(self, self.initarg1, self.initarg2, arg3, arg4)
    
您不需要instancemethod装饰器,这应该可以工作:
class MyClass:
  class fun:
    def __init__( self, parent, *args ):
      self.parent = parent
      self.args = args

m = MyClass()
f = m.fun(None, 1, 2, 3)
print f.args
您也可以将第一个示例更改为
class Props:
    def __init__( self, parent, *args ):
        self.parent = parent
        self.args = args


class MyClass:
    fun = Props

m = MyClass()
f = m.fun(None, 1, 2, 3)
print f.args
    

要回复问题请先登录注册