更新时间:2022-12-16 20:13:21
所有方法的第一个参数通常称为 self
.它指的是为其调用方法的实例.
The first argument of all methods is usually called self
. It refers to the instance for which the method is being called.
假设您有:
class A(object):
def foo(self):
print 'Foo'
def bar(self, an_argument):
print 'Bar', an_argument
然后,做:
a = A()
a.foo() #prints 'Foo'
a.bar('Arg!') #prints 'Bar Arg!'
这个被称为 self
并没有什么特别之处,你可以执行以下操作:
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()
然后,做:
b = B()
b.bar() # prints 'Foo'
在您的具体情况下:
In your specific case:
dangerous_device = MissileDevice(some_battery)
dangerous_device.move(dangerous_device.RIGHT)
(正如评论中所建议的,MissileDevice.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!