self
word in Python? I understand it refers to the specific object created from that class, but I can’t see why it explicitly needs to be added to every function as a parameter. To illustrate, in Ruby I can do this:class myClass def myFunc(name) @name = name end end
self
:class myClass: def myFunc(self, name): self.name = name
self.
is because Python does not use the @
syntax to refer to instance attributes. Python decided to do methods in a way that makes the instance to which the method belongs be passed automatically, but not received automatically: the first parameter of methods is the instance the method is called on. That makes methods entirely the same as functions, and leaves the actual name to use up to you (although self
is the convention, and people will generally frown at you when you use something else.) self
is not special to the code, it’s just another object.self.
.class Vector(object): def __init__(self, x, y): self.x = x self.y = y
def length(self): return math.sqrt(self.x ** 2 + self.y ** 2)
def length_global(vector): return math.sqrt(vector.x ** 2 + vector.y ** 2)
length
method for our Vector
class, we could do this:Vector.length_new = length_global v = Vector(3, 4) print v.length_new() # 5.0
length_global
, can be re-used as the self
parameter in length_new
. This would not be possible without an explicit self
.self
is to see where Python adds some syntactical sugar. When you keep in mind, that basically, a call likev_instance.length()
Vector.length(v_instance)
self
fits in. You don’t not actually write instance methods in Python; what you write is class methods which (must) take an instance as a first parameter. And therefore, you’ll have to place the instance parameter somewhere explicitly.
友情链接
深圳车辆实时定位物联网无线通信有限公司
========================
如需友情链接,发邮件到 lanchh@live.com 联系
========================
志文工作室
厦门地铁
云轻灵网络科技有限公司