[英]Passing the class as a default argument for its method
Here is the minimal Point
class needed for this question. 这是此问题所需的最小
Point
类。
class Point:
def __init__(self, x = 0, y = 0):
self.x = x
self.y = y
def dist_from(self, point = Point(0, 0)):
return ((self.x-point.x)**2 + (self.y-point.y)**2)**0.5
I want the dist_from
method to return the distance from origin if no point is passed. 如果没有传递点,我希望
dist_from
方法返回原点的距离。 And since method overloading is not possible, I decided to pass a Point
object (the origin) as the default value. 由于无法进行方法重载,因此我决定将
Point
对象(原点)作为默认值传递。
But I am missing something very fundamental. 但我遗漏了一些非常基本的东西。
Traceback (most recent call last):
File "C:\Users\Naveen\Desktop\temp.py", line 26, in <module>
class Point:
File "C:\Users\Naveen\Desktop\temp.py", line 32, in Point
def dist_from(self, point = Point(0, 0)):
NameError: name 'Point' is not defined
Default values are expressions that get evaluated when the function object is compiled. 默认值是在编译函数对象时得到的表达式。 The look-up for
Point
will fail since the class named Point
hasn't been created at that point. Point
的查找将失败,因为此时尚未创建名为Point
的类。
This can be side stepped by supplying a default value of None
for the default and act on that fact inside the method body (where the name Point
has been defined: 这可以通过为默认值提供默认值
None
来执行,并在方法体内执行该事实(其中已定义名称Point
:
def dist_from(self, point = None):
if point is None:
point = type(self)(0, 0) # Could do Point(0, 0)
return (self.x*point.x + self.y*point.y)**0.5
I'm using type(self)
here instead of Point
so as to not hard-code the class name in there. 我在这里使用
type(self)
而不是Point
,以便不在那里硬编码类名。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.