【问题标题】:python: is this a good way to use the same function name for both classmethod and method?python:这是对类方法和方法使用相同函数名的好方法吗?
【发布时间】:2013-02-01 09:22:09
【问题描述】:
class A(object):

    @classmethod
    def print(cls):
        print 'A'

    def __print(self):
        print 'B'

    def __init__(self):
        self.print = self.__print


a = A()
a.print()
A.print()

我觉得太丑了,有没有其他方法可以实现相同的功能?不要说 combinemethod,因为它每次都会创建一个对象。

【问题讨论】:

  • 这有什么意义?你想达到什么目的?
  • 我尝试为类方法和方法使用相同的函数名。
  • 例如,我们想通过 id 对记录进行分片。我们使用 A.get_db_name(id=1) 来计算新记录的数据库名称。我们还可以使用 a.get_db_name() 来获取已存在记录的数据库名称。

标签: python static-methods class-method


【解决方案1】:

最简单的解决方案是创建一个像classmethod 这样的描述符装饰器,但它也会将实例传递给方法:

from functools import partial
class descriptormethod(object):
    def __init__(self, fn):
        self.fn = fn
    def __get__(self, instance, owner):
        return partial(self.fn, instance, owner)

class A(object):
    @descriptormethod
    def print_(self, cls):
        print 'A' if self is None else 'B'

不用担心描述符或部分对象的开销;这与你正常调用实例或类方法时发生的情况没有什么不同。

【讨论】:

    猜你喜欢
    • 2012-07-20
    • 1970-01-01
    • 2011-05-17
    • 1970-01-01
    • 2012-06-02
    • 2011-04-08
    • 1970-01-01
    • 2011-03-05
    • 1970-01-01
    相关资源
    最近更新 更多