如何调用类中的函数?
我有这段代码可以计算两个坐标之间的距离。这两个函数都在同一个类中。
但是,如何在函数 isNear
中调用函数 distToPoint
呢?
class Coordinates:
def distToPoint(self, p):
"""
Use pythagoras to find distance
(a^2 = b^2 + c^2)
"""
...
def isNear(self, p):
distToPoint(self, p)
...
I have this code which calculates the distance between two coordinates. The two functions are both within the same class.
However, how do I call the function distToPoint
in the function isNear
?
class Coordinates:
def distToPoint(self, p):
"""
Use pythagoras to find distance
(a^2 = b^2 + c^2)
"""
...
def isNear(self, p):
distToPoint(self, p)
...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
由于这些是成员函数,因此将其作为实例
self
上的成员函数进行调用。Since these are member functions, call it as a member function on the instance,
self
.这是行不通的,因为
distToPoint
在你的类内部,所以如果你想引用它,你需要在它前面加上类名前缀,如下所示:classname.distToPoint(self, p)
。但你不应该那样做。更好的方法是直接通过类实例(类方法的第一个参数)引用该方法,如下所示:self.distToPoint(p)
。That doesn't work because
distToPoint
is inside your class, so you need to prefix it with the classname if you want to refer to it, like this:classname.distToPoint(self, p)
. You shouldn't do it like that, though. A better way to do it is to refer to the method directly through the class instance (which is the first argument of a class method), like so:self.distToPoint(p)
.在OP中,
distToPoint()
和isNear()
都是实例方法,因此,两者都引用一个实例(通常名为self) 作为它的第一个参数。当直接从实例调用实例方法时,引用会隐式传递,因此
有效。
如果您想从子类调用重写的父方法,则可以/应该使用
super()
。在下面的示例中,greet()
方法在Parent
和Child
类中定义,如果您想调用Parent
code>的greet()
,规定的方式是通过super()
,即super().greet()
。也可以通过类名来完成此操作,即Parent.greet(self)
但有很多反对这种硬编码而支持super()
的论点,例如灵活性、正确使用方法解析顺序的能力等。In the OP,
distToPoint()
andisNear()
are both instance methods and as such, both take a reference to an instance (usually namedself
) as its first argument. When an instance method called directly from the instance, the reference is passed implicitly, soworks.
If you want to call an overridden parent method from the child class, then
super()
could/should be used. In the following example,greet()
method is defined in bothParent
andChild
classes and if you want to callParent
'sgreet()
, the prescribed way is viasuper()
, i.e.super().greet()
. It's also possible to do it via the class name, i.e.Parent.greet(self)
but there are many arguments against such hard-coding in favor ofsuper()
such as flexibility, the ability to use method resolution order correctly etc.在上面的场景中,您尝试从同一类中定义的另一个成员方法访问成员方法。
要实现此目的,您必须在
distToPoint(self, p)
之前使用 self 关键字,如下所示:self.distToPoint(self, p)
来调用distToPoint(来自
方法。isNear(self, p)
的 self, p)希望这有帮助。
In the above scenario, you are trying to access a member method from another member method defined within the same class.
To achieve this you have to use the self keyword before
distToPoint(self, p)
like this:self.distToPoint(self, p)
to invoke thedistToPoint(self, p)
method fromisNear(self, p)
.Hope this helps.