Python中的静态方法和实例方法 [英] Static and instance methods in Python

查看:104
本文介绍了Python中的静态方法和实例方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以同时将Python方法定义为静态方法和实例方法吗?像这样:

Can I define a Python method to be both static and instance at the same time? Something like:

class C(object):
    @staticmethod
    def a(self, arg1):
        if self:
            blah
        blah

这样我就可以同时使用它:

So that I can call it with both:

C.a(arg1)
C().a(arg1)

目的是能够运行两组逻辑.如果作为实例方法进行访问,它将利用实例变量进行处理.如果将访问方式作为静态方法,则不会这样做.

The intent is to be able to run two sets of logics. If accessed as an instance method, it would make use of instance variables and do stuff. If access as a static method, it will do without.

推荐答案

import functools

class static_or_instance(object):
  def __init__(self, func):
    self.func = func

  def __get__(self, instance, owner):
    return functools.partial(self.func, instance)

class C(object):
  @static_or_instance
  def a(self, arg):
    if self is None:
      print "called without self:", arg
    else:
      print "called with self:", arg

C.a(42)
C().a(3)

这篇关于Python中的静态方法和实例方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆