简体   繁体   English

Python中的Python调用方法

[英]Python calling method in class

I'm punching way above my weight here, but please bear with this Python amateur. 我在这里超过了我的体重,但请忍受这个Python业余爱好者。 I'm a PHP developer by trade and I've hardly touched this language before. 我是一名PHP开发人员,我之前几乎没有接触过这种语言。

What I'm trying to do is call a method in a class...sounds simple enough? 我想要做的是在课堂上调用一个方法......听起来很简单? I'm utterly baffled about what 'self' refers to, and what is the correct procedure to call such a method inside a class and outside a class. 我完全不知道“自我”指的是什么,以及在课堂内和课堂外调用这种方法的正确程序是什么。

Could someone explain to me, how to call the move method with the variable RIGHT . 有人可以向我解释 ,如何使用变量RIGHT调用move方法。 I've tried researching this on several 'learn python' sites and searches on StackOverflow, but to no avail. 我试过在几个'学习python'网站上研究这个并在StackOverflow上搜索,但无济于事。 Any help will be appreciated. 任何帮助将不胜感激。

The following class works in Scott's Python script which is accessed by a terminal GUI (urwid). 以下类在Scott的Python脚本中工作,该脚本由终端GUI(urwid)访问。

The function I'm working with is a Scott Weston's missile launcher Python script, which I'm trying to hook into a PHP web-server. 我正在使用的功能是Scott Weston的导弹发射器Python脚本,我试图将其挂钩到PHP Web服务器。

class MissileDevice:
  INITA     = (85, 83, 66, 67,  0,  0,  4,  0)
  INITB     = (85, 83, 66, 67,  0, 64,  2,  0)
  CMDFILL   = ( 8,  8,
                0,  0,  0,  0,  0,  0,  0,  0,
                0,  0,  0,  0,  0,  0,  0,  0,
                0,  0,  0,  0,  0,  0,  0,  0,
                0,  0,  0,  0,  0,  0,  0,  0,
                0,  0,  0,  0,  0,  0,  0,  0,
                0,  0,  0,  0,  0,  0,  0,  0,
                0,  0,  0,  0,  0,  0,  0,  0)
  STOP      = ( 0,  0,  0,  0,  0,  0)
  LEFT      = ( 0,  1,  0,  0,  0,  0)
  RIGHT     = ( 0,  0,  1,  0,  0,  0)
  UP        = ( 0,  0,  0,  1,  0,  0)
  DOWN      = ( 0,  0,  0,  0,  1,  0)
  LEFTUP    = ( 0,  1,  0,  1,  0,  0)
  RIGHTUP   = ( 0,  0,  1,  1,  0,  0)
  LEFTDOWN  = ( 0,  1,  0,  0,  1,  0)
  RIGHTDOWN = ( 0,  0,  1,  0,  1,  0)
  FIRE      = ( 0,  0,  0,  0,  0,  1)

  def __init__(self, battery):
    try:
      self.dev=UsbDevice(0x1130, 0x0202, battery)
      self.dev.open()
      self.dev.handle.reset()
    except NoMissilesError, e:
      raise NoMissilesError()

  def move(self, direction):
    self.dev.handle.controlMsg(0x21, 0x09, self.INITA, 0x02, 0x01)
    self.dev.handle.controlMsg(0x21, 0x09, self.INITB, 0x02, 0x01)
    self.dev.handle.controlMsg(0x21, 0x09, direction+self.CMDFILL, 0x02, 0x01)

The first argument of all methods is usually called self . 所有方法的第一个参数通常称为self It refers to the instance for which the method is being called. 它指的是调用该方法的实例。

Let's say you have: 假设你有:

class A(object):
    def foo(self):
        print 'Foo'

    def bar(self, an_argument):
        print 'Bar', an_argument

Then, doing: 然后,做:

a = A()
a.foo() #prints 'Foo'
a.bar('Arg!') #prints 'Bar Arg!'

There's nothing special about this being called self , you could do the following: 这被称为self没什么特别的,你可以做到以下几点:

class B(object):
    def foo(self):
        print 'Foo'

    def bar(this_object):
        this_object.foo()

Then, doing: 然后,做:

b = B()
b.bar() # prints 'Foo'

In your specific case: 在您的具体情况:

dangerous_device = MissileDevice(some_battery)
dangerous_device.move(dangerous_device.RIGHT) 

(As suggested in comments MissileDevice.RIGHT could be more appropriate here!) (正如评论中所建议的那样, MissileDevice.RIGHT可能更合适!)

You could declare all your constants at module level though, so you could do: 可以在模块级别声明所有常量,所以你可以这样做:

dangerous_device.move(RIGHT)

This, however, is going to depend on how you want your code to be organized! 但是,这取决于您希望如何组织代码!

Let's say you have a shiny Foo class. 假设你有一个闪亮的Foo类。 Well you have 3 options: 那么你有3个选择:

1) You want to use the method (or attribute) of a class inside the definition of that class: 1)您希望在该类的定义中使用类的方法(或属性):

class Foo(object):
    attribute1 = 1                   # class attribute (those don't use 'self' in declaration)
    def __init__(self):
        self.attribute2 = 2          # instance attribute (those are accessible via first
                                     # parameter of the method, usually called 'self'
                                     # which will contain nothing but the instance itself)
    def set_attribute3(self, value): 
        self.attribute3 = value

    def sum_1and2(self):
        return self.attribute1 + self.attribute2

2) You want to use the method (or attribute) of a class outside the definition of that class 2)您希望使用该类定义之外的类的方法(或属性)

def get_legendary_attribute1():
    return Foo.attribute1

def get_legendary_attribute2():
    return Foo.attribute2

def get_legendary_attribute1_from(cls):
    return cls.attribute1

get_legendary_attribute1()           # >>> 1
get_legendary_attribute2()           # >>> AttributeError: type object 'Foo' has no attribute 'attribute2'
get_legendary_attribute1_from(Foo)   # >>> 1

3) You want to use the method (or attribute) of an instantiated class: 3)您想要使用实例化类的方法(或属性):

f = Foo()
f.attribute1                         # >>> 1
f.attribute2                         # >>> 2
f.attribute3                         # >>> AttributeError: 'Foo' object has no attribute 'attribute3'
f.set_attribute3(3)
f.attribute3                         # >>> 3

Could someone explain to me, how to call the move method with the variable RIGHT 有人可以向我解释,如何使用变量RIGHT调用move方法

>>> myMissile = MissileDevice(myBattery)  # looks like you need a battery, don't know what that is, you figure it out.
>>> myMissile.move(MissileDevice.RIGHT)

If you have programmed in any other language with classes, besides python, this sort of thing 如果您已经使用任何其他语言编写了类,除了python之外,还有类似的东西

class Foo:
    bar = "baz"

is probably unfamiliar. 可能不熟悉。 In python, the class is a factory for objects, but it is itself an object; 在python中,类是对象的工厂,但它本身就是一个对象; and variables defined in its scope are attached to the class , not the instances returned by the class. 和在其范围内定义的变量附加到 ,而不是返回的实例。 to refer to bar , above, you can just call it Foo.bar ; 要参考上面的bar ,你可以称之为Foo.bar ; you can also access class attributes through instances of the class, like Foo().bar . 您还可以通过类的实例访问类属性,如Foo().bar


Im utterly baffled about what 'self' refers too, 我对“自我”的含义完全感到困惑,

>>> class Foo:
...     def quux(self):
...         print self
...         print self.bar
...     bar = 'baz'
...
>>> Foo.quux
<unbound method Foo.quux>
>>> Foo.bar
'baz'
>>> f = Foo()
>>> f.bar
'baz'
>>> f
<__main__.Foo instance at 0x0286A058>
>>> f.quux
<bound method Foo.quux of <__main__.Foo instance at 0x0286A058>>
>>> f.quux()
<__main__.Foo instance at 0x0286A058>
baz
>>>

When you acecss an attribute on a python object, the interpreter will notice, when the looked up attribute was on the class, and is a function, that it should return a "bound" method instead of the function itself. 当你在python对象上使用一个属性时,解释器会注意到,当查找属性在类上时,它是一个函数,它应该返回一个“绑定”方法而不是函数本身。 All this does is arrange for the instance to be passed as the first argument. 所有这一切都安排将实例作为第一个参数传递。

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

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