每个对象调用后更改属性 [英] Change attribute after each object calling

查看:138
本文介绍了每个对象调用后更改属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出如何对象的每次通话后改变一些价值。
我thougt的拨打()函数每次通话后执行。

I'm trying to figure out how to change some value after each call of the object. I thougt that call() function is executed after each call.

这应该是一个简单的计数器类,它被称为后减小value属性。

This should be a simple counter class which decreases value attribute after being called.

class counter():
    def __init__(self,value):
        self.value = value

    def __call__(self):
        self.value -= 1

count = counter(50)
print count.value
print count.value

>> 50 
>> 50 <-- this should be 49

我是什么做错了吗?

What am I doing wrong?

推荐答案

如果你不承诺类,你可以使用函数和滥用使用可变类型,如默认初始化值:

If you're not committed to classes, you could use a function and abuse using mutable-types-as-default-initializers:

def counter(init=None, container=[0]):
    container[0] -= 1
    if init is not None: container[0] = init
    return container[0]


x = counter(100)
print(x) # 100
print( counter() )  # 99
print( counter() )  # 98
print( counter() )  # 97
# ...

呼叫计数带一个参数来设置/初始化计数器。由于初始化实际上是该函数的第一次调用,它将返回该号码。

Call counter with a single argument to set/initialize the counter. Since initialization is actually the first call to the function, it will return that number.

呼叫计数不带任何参数,以获得下一个值。

Call counter with no arguments to get the "next value".

(非常相似,我建议<一href=\"http://stackoverflow.com/questions/29092576/python-static-variable-generator-function/29093043#29093043\">here)

另外,对于语法更接近你在你的问题有哪些,使用性能

Alternatively, for a syntax closer to what you had in your question, use properties:

class Counter(object):
    def __init__(self, init):
        self.val = init

    @property
    def value(self):
        val = self.val
        self.val -= 1
        return val

count = Counter(50)

print(count.value)  # 50
print(count.value)  # 49
print(count.value)  # 48
print(count.value)  # 47
#...

在这里,你正在创建一个名为计数 A 计数对象,然后每次调用时间 count.value 它通过递减它的内部 VAL 属性返回当前值和prepares本身未来的呼叫。

Here, you're creating a Counter object called count, then every time you call count.value it returns the current value and prepares itself for a future call by decrementing it's internal val attribute.

此外,你第一次请求属性,它返回你初始化它的数量。

Again, the first time you request the value attribute, it returns the number you initialized it with.

如果由于某种原因,你想窥视在下次调用 count.value 将是什么,没有递减它,你可以看看 count.val 代替。

If, for some reason, you want to "peek" at what the next call to count.value will be, without decrementing it, you can look at count.val instead.

这篇关于每个对象调用后更改属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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