python 2中的函数可以是静态的还是非静态的 [英] can a function be static and non-static in python 2

查看:36
本文介绍了python 2中的函数可以是静态的还是非静态的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这门课:

类测试(对象):def __init__(self, a):self.a = a定义测试(自我,b):如果是实例(自我,测试):返回 self.a + b别的:返回 self + b

在我的世界中,理想情况下会这样做:

<预><代码>>>>测试.测试(1,2)3>>>测试(1).测试(2)3

现在这不起作用,因为您收到此错误:

TypeError: unbound method test() must be used with Test instance as first parameter ( got int instance instead)

在 python3 中,这工作正常,我偷偷怀疑这在 python2 中使用装饰器是可能的,但我的 python foo 不够强大,无法让它工作.

Plot Twist:那么当我需要一些东西而不是静态调用时会发生什么.

解决方案

如果你想要一些东西,如果在实例上调用,实际上会接收 self,但也可以在类上调用,写你的可能建议使用自己的描述符类型:

导入类型类类或实例方法(对象):def __init__(self,wrapped):self.wrapped = 包裹def __get__(self, instance, owner):如果实例是无:实例 = 所有者返回 self.wrapped.__get__(instance, owner)类演示(对象):@ClassOrInstanceMethoddef foo(self):# self 将是类,如果在类上调用它打印(自己)

演示.

对于您的问题的原始版本,您可以像任何其他静态方法一样使用 @staticmethod 编写它.在实例上调用静态方法与在类上调用它的工作原理相同:

类测试(对象):@静态方法定义测试(a,b):返回 a + b

演示.

Lets say I have this class:

class Test(object):
    def __init__(self, a):
        self.a = a

    def test(self, b):
        if isinstance(self, Test):
            return self.a + b
        else:
            return self + b

This would ideally in my world do this:

>>> Test.test(1,2)
3
>>> Test(1).test(2)
3

Now this doesn't work because you get this error:

TypeError: unbound method test() must be called with Test instance as first argument (got int instance instead)

In python3 this works fine, and I have the sneaking suspicion this is possible with a decorator in python2 but my python foo isn't strong enough to get that to work.

Plot Twist: So what happens when I need something on self when it's not called statically.

解决方案

If you want something that will actually receive self if called on an instance, but can also be called on the class, writing your own descriptor type may be advisable:

import types

class ClassOrInstanceMethod(object):
    def __init__(self, wrapped):
        self.wrapped = wrapped
    def __get__(self, instance, owner):
        if instance is None:
            instance = owner
        return self.wrapped.__get__(instance, owner)

class demo(object):
    @ClassOrInstanceMethod
    def foo(self):
        # self will be the class if this is called on the class
        print(self)

Demo.

For the original version of your question, you could just write it like any other static method, with @staticmethod. Calling a static method on an instance works the same as calling it on the class:

class Test(object):
    @staticmethod
    def test(a, b):
        return a + b

Demo.

这篇关于python 2中的函数可以是静态的还是非静态的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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