Python calling method in class

前端 未结 3 1330
予麋鹿
予麋鹿 2020-12-07 17:04

I\'m punching way above my weight here, but please bear with this Python amateur. I\'m a PHP developer by trade and I\'ve hardly touched this language before.

What I

3条回答
  •  天命终不由人
    2020-12-07 17:23

    Could someone explain to me, how to call the move method with the variable RIGHT

    >>> 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

    class Foo:
        bar = "baz"
    

    is probably unfamiliar. In python, the class is a factory for objects, but it is itself an object; 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; you can also access class attributes through instances of the class, like Foo().bar.


    Im utterly baffled about what 'self' refers too,

    >>> class Foo:
    ...     def quux(self):
    ...         print self
    ...         print self.bar
    ...     bar = 'baz'
    ...
    >>> Foo.quux
    
    >>> Foo.bar
    'baz'
    >>> f = Foo()
    >>> f.bar
    'baz'
    >>> f
    <__main__.Foo instance at 0x0286A058>
    >>> f.quux
    >
    >>> 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. All this does is arrange for the instance to be passed as the first argument.

提交回复
热议问题