简体   繁体   English

Python-类中的Function对象

[英]Python- Function object in class

class new:
    i=1
    def __init__(self):
        name='sakthi'

    def add(self,one,two):
         return one+two

k=new.add

print(k)

When I execute the above program. 当我执行以上程序时。 I get function new.add at 0x0068E270 as output. 我在function new.add at 0x0068E270获得了function new.add at 0x0068E270作为输出。

Can anyone help me to understand, what has happened and what kind of operation can I do with value k . 任何人都可以帮助我了解,发生了什么以及我可以使用值k哪种操作。

The new.add value you're assigning to k is a function. 您要分配给knew.add值是一个函数。 In Python 2, it would have been a special "unbound method" object, but your output suggests you're using Python 3 (where unbound methods don't exist any more except conceptually). 在Python 2中,它本来是一个特殊的“未绑定方法”对象,但是您的输出表明您正在使用Python 3(除了从概念上讲,已不再存在未绑定方法)。

Like any function, you can call k if you want, passing whatever values are appropriate for self , one and two . 像任何函数一样,可以根据需要调用k ,传递适合selfonetwo任何值。 For instance, k("foo", 1, 2) (which will return 3 ). 例如, k("foo", 1, 2) (将返回3 )。

Traditionally the self argument should be an instance of the new class, though in Python 3 that isn't enforced by anything (a check for this was the purpose of unbound method objects in Python 2). 传统上, self参数应该是new类的实例,尽管在Python 3中它没有任何作用(对此进行检查是Python 2中未绑定方法对象的目的)。 So passing a string in the example above worked fine, since self is not used in the function body for anything. 因此,在上面的示例中传递字符串的效果很好,因为函数主体中未使用self (More complicated methods will usually fail if you pass an inappropriate argument as self .) (如果您将不适当的参数作为self传递,则更复杂的方法通常会失败。)

The usual way to call methods is to create an instance of a class first, then call the method on the instance. 调用方法的通常方法是先创建一个类的实例,然后在该实例上调用该方法。 This causes the instance to be passed as the first argument automatically: 这将导致实例自动作为第一个参数传递:

x = new()
x.add(1, 2) # returns 3, x got passed as self

function new.add at 0x0068E270 In CPython, will be the address of k . function new.add at 0x0068E270在CPython中,将是k的地址。 Since k is just a function you can still do something like print(k('foo', 1, 2)) that Will print 5 由于k只是一个函数,您仍然可以执行诸如print(k('foo', 1, 2)) ,该操作将打印5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM