如何使用classmethod初始化类成员

时间:2017-08-08 11:26:24

标签: python oop class-method

我有一个类,它包含一些成员class Foo(object): x = 23 # some more code goes here (例如,所有实例都需要的一些数据,但与它们无关):

x

现在,确定x的过程变得更加复杂,而且我希望能够在某些时间“刷新”class Foo(object): @classmethod def generate_x(cls): cls.x = 23 # some more code goes here ,所以我决定为它编写额外的功能

generate_x

但是,此类定义缺少class Foo(object): # generate_x() # NameError: name 'generate_x' is not defined # Foo.generate_x() # NameError: name 'Foo' is not defined @classmethod def generate_x(cls): cls.x = 23 的初始化调用。

到目前为止我尝试了什么:

这不起作用:

class Foo(object):

    @classmethod
    def generate_x(cls):
        cls.x = 23

    # ...
Foo.generate_x()

这可行但不太清楚,因为代码在类定义之外使用

@classmethod

有更好的替代品吗?在这里使用__init__是最好的方法吗?我正在搜索的是类Foo.x

考虑到代码清晰度,有没有比后者更好的方法来自动使用函数实例化 .pager-next { padding-right: 0; } .pagination-btn > div > span { display: inline-block; height: 21px; width: 21px; } .pager-next span { background: hsla(0, 0%, 0%, 0) url(".....images/next.png") no-repeat scroll center center; float: right; margin-left: 8px; } // for previous arrow .pager-prev, .pager-next { float: left; padding: 0 20px; } .pagination-btn > div > span { display: inline-block; height: 21px; width: 21px; } .pager-prev span { background: hsla(0, 0%, 0%, 0) url("...........images/prev.png") no-repeat scroll center center; float: left; margin-right: 8px; } // Pagination php code global $paged; if(empty($paged)) $paged = 1; $args = array( 'paged' => $paged, 'posts_per_page' => 9, ); $args['cat'] = get_query_var('cat'); $cat_post = new WP_Query( $args ); if ( $cat_post->have_posts() ) : while ($cat_post->have_posts()) : $cat_post->the_post(); ................ endwhile; else : ?> <p><?php _e('Apologies, but no entries were found.', 'tb'); ?></p> <?php endif; <?php if ($cat_post->max_num_pages > 1) { ?> <div class="pager-prev"> <?php if (!empty(get_previous_posts_link( ' Previous' ))) { echo '<span></span>'.get_previous_posts_link( 'Previous' ); } ?> </div> <div class="pager-next"> <?php if (!empty(get_next_posts_link( 'Next'))) { echo get_next_posts_link( 'Next').'<span></span>'; } ?> </div> <?php } ?>

2 个答案:

答案 0 :(得分:1)

实现这一目标的一种方法是使用装饰器:

def with_x(cls):
   cls.generate_x()
   return cls

@with_x
class Foo(object):
   @classmethod
   def generate_x(cls):
      cls.x = 23

(也就是说,我个人只会在课堂宣言后明确地致电Foo.generate_x,并完全避免所有的魔法。)

答案 1 :(得分:0)

使用描述符。

class Complicated:
    def __init__(self, location, get_value):
        self.location =location 
        self.get_value = staticmethod(get_value)
    def __get__(self, obj, owner):
        try:
            a = getattr(owner, self.location)
        except AttributeError:
            a = self.get_value()
            setattr(owner, self.location, a)
        return a

class My class:
     x = Complicated ('_x', get_x)