def draw_rect(rect):
# code to draw a rect here
def draw_line(line):
# code to draw a line here
def draw_circle(circle):
# code to draw a circle here
def draw_all(drawables):
for obj in drawables:
if isinstance(obj, Rect):
draw_rect(obj)
elif isinstance(obj, Line):
draw_line(obj)
elif isinstance(obj, Circle):
draw_circle(obj)
def main():
# a list of various "drawable" objects
objects = [Rect(), Line(), Cicle()]
draw_all(objects)
对于对象:
class Rect():
def draw(self):
# code to draw a rect here
class Line():
def draw(self):
# code to draw a line here
class Circle():
def draw(self):
# code to draw a circle here
def draw_all(drawables):
for obj in drawables:
obj.draw()
def main():
# a list of various "drawable" objects
objects = [Rect(), Line(), Cicle()]
draw_all(objects)
因为没有什么可以传递给函数了。或者,更准确地说(假设
df
类似于panda dataframe实例或其他类似对象),因为在本例中,唯一需要的参数(df
)是自动传递给函数的如果你真的想做的话,你可以做一些像
type(df).corr(df)
的事情,但那有点没用好的,让我们更深入一点:Python是一个object oriented language。在OO中,对象具有“方法”——作用于调用对象的函数。在大多数OOPL中,方法调用的语法是
obj.method()
,而不是method(obj)
。在幕后,您的语言的编译器或解释器(或任何其他机制)实际上使obj
可用于该方法,因此无需显式地传递它采用这种方式而不是使用标准函数的意义在于,不同的对象可以各自以自己的方式定义相同的方法,因此作为这些对象的“客户机”,您不必检查确切的类型并自己调用特定于对象的版本,即:
无对象:
对于对象:
在幕后,Python将把
obj.draw()
变成type(obj).draw(obj)
。这被称为“基于类型的多态调度”,实际上是OOP中最基本的概念现在Python不是一个“纯”的OOPL,因为in不会强迫您只使用对象和方法-您也可以编写和使用普通函数(例如上面的
draw_all
和main
函数),当然,这些函数将按照您的预期工作相关问题 更多 >
编程相关推荐