简体   繁体   English

在python中,有什么优雅的方法可以在类声明范围内引用类方法?

[英]In python, any elegant way to refer to class method within the classes declaration scope?

The below code works both under Python 2.6 and 3.1, but the third lambda of SomeObject.columns is a bit silly, serving no real purpose but to prevent the reference to SomeObject.helper_function from being looked at before the class declaration finishes. 下面的代码在Python 2.6和3.1下都可以使用,但是SomeObject.columns的第三个lambda有点愚蠢,没有任何实际目的,只是防止在类声明完成之前查看对SomeObject.helper_function的引用。 It seems like a hack. 好像是hack。 If I remove the lambda, and replace it with just SomeObject.helper_function , I get NameError: name 'SomeObject' is not defined . 如果删除lambda,然后仅将其替换为SomeObject.helper_functionSomeObject.helper_function NameError: name 'SomeObject' is not defined Am I missing a better non-hacky way? 我是否错过了一种更好的非黑客方式?

class SomeObject:
  def __init__(self, values):
    self.values = values

  @staticmethod
  def helper_function(row):
    # do something fancy here
    return str(len(row))

  columns = [
    (lambda x: x['type'], 'Type'),
    (lambda x: 'http://localhost/view?id=%s' % x['id'], 'Link'),
    (lambda x: SomeObject.helper_function(x), 'Data'),
    ]

  def render_table_head(self):
    print('\t'.join([c[1] for c in self.columns]))

  def render_table_body(self):
    for row in self.values:
      print('\t'.join([col[0](row) for col in self.columns]))

There's no way to refer to the class that's currently being defined. 无法引用当前正在定义的类。 There should really be keywords referring to the current scope, eg. 确实应该有关键字引用当前范围,例如。 __this_class__ for the innermost class being defined and __this_func__ for the innermost function, so classes and functions can cleanly refer to themselves without having to repeat their name. __this_class__用于定义的最内层类)和__this_func__用于定义的最内层函数),因此类和函数可以干净地引用自己,而不必重复其名称。

You could move the definition of columns out of the class body: 您可以将列的定义移出类主体:

class SomeObject:
    def __init__(self, values):
        self.values = values
    ...

SomeObject.columns = [
    (lambda x: x['type'], 'Type'),
    (lambda x: 'http://localhost/view?id=%s' % x['id'], 'Link'),
    (SomeObject.helper_function, 'Data'),
]

By the way, please always use at least 4-space indentation. 顺便说一句,请始终使用至少4个空格的缩进。 Anything less is very hard to read. 什么都不是很难读。

Why not populate columns in init () and use self? 为什么不填充init ()中的列并使用self?

def __init__(self, values):
    self.values = values
    self.columns = [
        (lambda x: x['type'], 'Type'),
        (lambda x: 'http://localhost/view?id=%s' % x['id'], 'Link'),
        (self.helper_function, 'Data'),
    ]

This works. 这可行。 It goes against all of my sensibilities. 它违背了我所有的感觉。

class SomeObject:
  def __init__(self, values):
    self.values = values

  def helper_function(row):
    # do something fancy here
    return str(len(row))

  columns = [
    (lambda x: x['type'], 'Type'),
    (lambda x: 'http://localhost/view?id=%s' % x['id'], 'Link'),
    (helper_function, 'Data'),
    ]

  def render_table_head(self):
    print('\t'.join([c[1] for c in self.columns]))

  def render_table_body(self):
    for row in self.values:
      print('\t'.join([col[0](row) for col in self.columns]))


if __name__ == '__main__':
    print "foo"

    o = SomeObject([{'type':'type100', 'id':'myId'}, {'type':'type200', 'id':'myId2'}])
    o.render_table_body()

You can directly refer to the static function through 您可以通过直接引用静态函数

(helper_function.__func__, 'Data'),

without having to change anything else in your code. 无需更改代码中的任何其他内容。 helper_function is of type staticmethod , and __func__ gives access to the underlying function. helper_function的类型为staticmethod ,并且__func__允许访问基础函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM