功能与方法 [英] function v. method

查看:80
本文介绍了功能与方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

起初我打算发布以下信息:


<! - 我的原始帖子的开头 - >


我刚发现了inspect模块,它包含isfunction和

ismethod函数。出于某种原因,我曾经在印象中认为Python方法与Python函数没有什么不同。当然,

我想知道为什么这两个都需要存在(我后来发现了

的isroutine函数)。所以我开始在提示实验。这是我所做的

At first I was going to post the following:

<!-- beginning of my original post -->

I just discovered the inspect module, which contains the isfunction and
ismethod functions. For some reason, I used to be under the impression
that Python methods are no different from Python functions. Naturally,
I wondered why both of these needed to exist (I also later discovered
the isroutine function). So I started to experiment at prompt. Here''s
what I did:


> >来自inspect import *
def dan():传递
>>from inspect import *
def dan(): pass



....

....


>> ismethod(dan)
>>ismethod(dan)



False

False


>> isfunction(dan)
>>isfunction(dan)



True

True


>>类Foo:
>>class Foo:



.... def meth(self):pass

....

.... def meth(self): pass
....


>> m = Foo.meth
m
>>m = Foo.meth
m



< unbound method Foo .meth>

<unbound method Foo.meth>


>> ismethod(m)
>>ismethod(m)



True

True


>> ; Foo.func = dan#< - 显然,这里发生了一些神奇的事情,因为......
Foo.func
>>Foo.func = dan # <-- Appearantly, something magical happens here, because...
Foo.func



< unbound method Foo.dan>

<unbound method Foo.dan>


>> f = Foo.func
f是dan#< ; - 事情在这里开始变得令人惊讶。
>>f = Foo.func
f is dan # <-- things begins to look suprising here.



False

False


>> ismethod(f)
>>ismethod(f)



True


想象一下我的惊讶。为什么Python会这样做?


<! - 我的原始帖子的结尾,结束审查 - >


但是我试过这个:

True

Imagine my surprise. Why would Python do this?

<!-- end of my original post, with ending censored -->

but then I tried this:


>> res = Foo .__ dict __ [''func' ']
res是dan
>>res = Foo.__dict__[''func'']
res is dan



True


一切都开始了有意义。令人惊讶的事情结果是

并不那么令人惊讶:当表达式Foo.func被评估时,我们得到

一个方法,它只是dan的包装器。因此,f不是dan!


这仍然有点神奇,让我再次思考

我自我审查的东西。由于点语法在我的情况下做了一些特殊的

和意外,为什么不使用更多的点魔法来实现

privates?私人没有必要完全缺席Klass .__ dict__

(这会使Python不具有内省性);使用点语法时,它们只能是隐形的




顺便说一句,我知道Python的名称修改功能。

True

And it all started to make sense. The surprising thing turned out to be
not so surprising: When the expression Foo.func gets evaluated, we get
a method which is just a wrapper around dan. Therefore, f is not dan!

This is still a little bit of magic, which gets me thinking again about
the stuff I self-censored. Since the dot syntax does something special
and unexpected in my case, why not use some more dot-magic to implement
privates? Privates don''t have to be entirely absent from Klass.__dict__
(which would make Python not introspective); they can just be invisible
when using the dot-syntax.

BTW, I am aware of Python''s name mangling feature.

推荐答案

我猜python开发人员对实现一些需要新语法并且不提供某些东西的
不感兴趣完全新的

语言。


关于python的好处是,开发人员只实现了

的想法很酷。在被拒绝的人群中有很多很酷的(!=非常酷的)想法

- 但是他们从来没有被充分理由实施。


如果你真的* *需要私有,只需使用命名约定。

I guess the python devs are not interested in implementing something
that would require new syntax and does not give something entirely new
to the language.

The good thing about python is, that the devs are only implementing
ideas that are very cool. There are a lot of cool (!= very cool) ideas
in rejected peps - but they were never implemented for good reasons.

If you *really* need privates, just use the naming convention.


danielx写道:
danielx wrote:

这是还是有点神奇,这让我再次想到了我自我审查的东西。由于点语法在我的情况下做了一些特殊的

和意外,为什么不使用更多的点魔法来实现

privates?私人没有必要完全缺席Klass .__ dict__

(这会使Python不具有内省性);当使用点语法时,它们只能是隐形的


This is still a little bit of magic, which gets me thinking again about
the stuff I self-censored. Since the dot syntax does something special
and unexpected in my case, why not use some more dot-magic to implement
privates? Privates don''t have to be entirely absent from Klass.__dict__
(which would make Python not introspective); they can just be invisible
when using the dot-syntax.



你现在可以这样做,有点:

You can do this now, kind of:


>>类Foo(对象):
>>class Foo(object):



.... x = property()

.... def doStuffWithX(self):

.... self .__ dict __ [''x''] = 123

.... print self .__ dict __ [''x'']

....

.... x = property()
.... def doStuffWithX(self):
.... self.__dict__[''x''] = 123
.... print self.__dict__[''x'']
....


>> bar = Foo()
bar.doStuffWithX()
>>bar = Foo()
bar.doStuffWithX()



123

123


>> bar.x
>>bar.x



回溯(最近一次调用最后一次):

文件"< stdin>",第1行,在?

AttributeError:不可读的属性


如果你提出self.x和bar.x应该给出不同的结果,那么这比魔法()和方法使用更加神奇。他们

都使用描述符API;有关详细信息,请阅读

< http://python.org/download/releases/2.2.3/descrintro/>。

Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: unreadable attribute

If you''re proposing that self.x and bar.x should give different results,
then that''s quite a bit more magic than property() and methods use. They
both use the descriptor API; for more information on that, read
<http://python.org/download/releases/2.2.3/descrintro/>.


danielx写道:
danielx wrote:

>>> Foo.func = dan# < - 好的,这里发生了一些神奇的事情,
>>>Foo.func = dan # <-- Appearantly, something magical happens here,



因为......

because...


>>> Foo.func
>>>Foo.func


< unbound method Foo.dan>

<unbound method Foo.dan>


>>> f = Foo.func
f是dan#< - 事情开始看起来很惊讶。
>>>f = Foo.func
f is dan # <-- things begins to look suprising here.



False

False


>>> ; ismethod(f)
>>>ismethod(f)



True


想象一下我的惊讶。为什么Python会这样做?

True

Imagine my surprise. Why would Python do this?



在你说的那一点上没有任何神奇的事情发生。赋值只是一个

赋值,你看到当你在班级词典中查看
时函数是否保持不变。


访问类或实例的成员时会发生魔术。如果

该值是描述符,则调用其__get__方法。大概说来,
说,Foo.func相当于:

Nothing magical happens at the point you said. The assignment is just an
assignment and you saw that the function was stored unchanged when you
looked in the class''s dictionary.

The magic happens when you access a member of a class or an instance. If
the value is a descriptor then its __get__ method is called. Roughly
speaking, Foo.func is equivalent to:


>> Foo .__ dict __ [''func''] .__ get __(None,Foo)
>>Foo.__dict__[''func''].__get__(None, Foo)



< unbound method Foo .dan>


Python这样做可以支持其他描述符类型,例如

property,classmethod,staticmethod。


如果你定义自己的描述符,你会发现这种情况:

<unbound method Foo.dan>

Python does this so that it can support other descriptor types such as
property, classmethod, staticmethod.

You can see this happening if you define your own descriptor:


> >类MyDesc(对象):
>>class MyDesc(object):



def __get __(self,* args):

打印__ get__被叫,args

返回无

def __get__(self, *args):
print "__get__ called", args
return None


>> d = MyDesc()
Foo.oops = d
.Foo.oops
>>d = MyDesc()
Foo.oops = d
Foo.oops



__get__调用(无,<类__main__.Foo在0x00B3F930>)

http://docs.python.org/ref/descriptor- invocation.html 有一个描述

这个。虽然它声称注意,仅对新的
样式对象或类(子类object()或type())调用描述符。

描述符机制部分是针对旧式类实现的。

描述符的几个方面虽然在旧式中不能正常工作

这是你应该总是使用新式课程的一个原因。

__get__ called (None, <class __main__.Foo at 0x00B3F930>)

http://docs.python.org/ref/descriptor-invocation.html has a description of
this. Although it claims "Note that descriptors are only invoked for new
style objects or classes (ones that subclass object() or type())." the
descriptor mechanism is partially implemented for old style classes.
Several aspects of descriptors don''t work properly though in old-style
classes which is one reason why you should always use new-style classes.


私人不必完全缺席Klass .__ dict__

(这会使Python不具有内省性);当使用点语法时,它们只能是隐形的


Privates don''t have to be entirely absent from Klass.__dict__
(which would make Python not introspective); they can just be invisible
when using the dot-syntax.



您可以使用数据描述符实现它,但是如果您打算使用点运算符阻止访问您的私有变量,b / b
然后你的

代码看起来很傻很多,引用了很多引用

self .__ dict __ [''theprivate'']它在可读性方面没有任何好处结束

self .__ theprivate。

You could implement that using a data descriptor, but if you are going to
prevent access to your private variables using the dot operator, then your
code is going to look pretty silly with a lot of references to
self.__dict__[''theprivate''] which doesn''t gain anything in readability over
self.__theprivate.


这篇关于功能与方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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