python:这是为类方法和方法使用相同函数名的好方法吗?

标签 python static-methods class-method

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,因为它每次都会创建一个对象。

最佳答案

最简单的解决方案是创建一个像 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'

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

关于python:这是为类方法和方法使用相同函数名的好方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14643092/

相关文章:

python - 如何在 python 中将 qwidgettable 中的列设置为会计格式?

python - 使用 dns.resolver (pythondns) 设置特定的 DNS 服务器

python - 为什么我不能在类方法中使用 python 模块 concurrent.futures?

javascript - Javascript 类中的静态变量

python - 树数据结构中的根节点操作

C++:方法中的字符串成员别名

python - 如何模拟使用 getattr 动态调用的请求方法

python - 有没有办法从所有 30 个数据帧中只提取一列?

php - laravel 如何在静态方法中使用 $this 上下文?

java - 在 Java 中,这些方法中哪种更好?