python传递对象作为参数

6 python oop object

如何在调用类方法时将对象作为参数传递给类方法并调用传递对象的方法?

说我有:

class myclass:
    def __init__(self):
        pass
    def myfunc(self, something):
        something.do()


anobject = blah.xyz()

another_obj = myclass()
another_obj.myfunc(anobject)
Run Code Online (Sandbox Code Playgroud)

Hug*_*ell 8

只要something有一个.do方法,它应该按照给定的方式工作(一旦你修改了缩进和声明的顺序).你试过运行吗?

这(或多或少)是许多标准函数的工作方式 - 例如,内置len函数非常多

def len(obj):
    return obj.__len__()
Run Code Online (Sandbox Code Playgroud)