简体   繁体   English

从Python中的类调用方法

[英]Calling a method from a class in Python

I know I'm just missing something simple here. 我知道我只是在这里缺少一些简单的东西。 I looked through other answers but couldn't find this problem. 我浏览了其他答案,但找不到此问题。

>>> class Ben:
...     """Can access variable but not method"""
...     i = 320894
...     def foo(self):
...             return i
... 
>>> Ben.i
320894
>>> Ben.foo(self)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'self' is not defined

You don't pass self yourself. 你不通过self自己。 It is a reference to an instance of the class on which you invoke that method. 它是对您在其上调用该方法的类的实例的引用。 So, you would need to create an instance of Ben , and invoke that method on that instance: 因此,您需要创建一个Ben实例,然后在该实例上调用该方法:

ben = Ben()
ben.foo()

And instead of: 而不是:

return i 

you need to use: 您需要使用:

return self.i

You need to instantiate a class instance in this case and invoke the method from that. 在这种情况下,您需要实例化一个类实例并从中调用该方法。

>>> class Ben:
    """Can access variable but not method"""
    i = 320894
    def foo(self):
        return self.i

>>> a = Ben()
>>> a.foo()
320894

PS - You don't pass self as an argument and you have to change the return statement to self.i . PS-您不必将self作为参数传递,而必须将return语句更改为self.i

You first must create an instance of the class. 您首先必须创建该类的实例。 "self" is automatically added as the first parameter, you can't pass it in yourself. “ self”会自动添加为第一个参数,您无法自己传递。

ben = Ben()
ben.foo()

Here are the various way I can think of (off the top 'o my head) to get a class attribute from an instance method: 这是我可以想到的各种方法(自上而下)来从实例方法获取类属性:

class Ben:
     i = 320894
     def foo(self):
        return self.i, self.__class__.i, Ben.i, Ben.__dict__['i'], getattr(Ben,'i')

print Ben().foo()  

Prints: 印刷品:

(320894, 320894, 320894, 320894, 320894)

Note the Ben().foo() vs Ben.foo(self) -- You need an instance of Ben prior to calling foo and self is implicit in the calling of foo as a method of that instance. 注意Ben().foo() vs Ben.foo(self) -在调用foo之前需要一个Ben实例,并且selffoo的调用中作为该实例的方法是隐式的。 If you have Ben().foo() the instance is created similarly to b=Ben() and then calling b.foo() 如果您有Ben().foo()则实例的创建类似于b=Ben() ,然后调用b.foo()

self.i or Ben.i is the most straightforward. self.iBen.i是最简单的。 Keep in mind that these can be different i's. 请记住,这些可能与我不同。 self.i is an instance attribute and Ben.i is a class attribute: self.i是实例属性,而Ben.i是类属性:

class Ben(object):
    i = 'class i'

    def __init__(self):
        self.i='instance i'

    def foo(self):
        return ('Instance i:',self.i, getattr(self,'i'), self.__dict__['i'],
                'Class i:',self.__class__.i, getattr(Ben,'i'), Ben.i, Ben.__dict__['i'])

print Ben().foo() 

Prints: 印刷品:

('Instance i:', 'instance i', 'instance i', 'instance i', 
 'Class i:', 'class i', 'class i', 'class i', 'class i')

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

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