Python calling method in class

前端 未结 3 1344
予麋鹿
予麋鹿 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:27

    The first argument of all methods is usually called 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:

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

    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!

提交回复
热议问题