Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python—是否存在一个在对象未实现函数时调用的函数?_Python_Oop_Function - Fatal编程技术网

Python—是否存在一个在对象未实现函数时调用的函数?

Python—是否存在一个在对象未实现函数时调用的函数?,python,oop,function,Python,Oop,Function,在Smalltalk中,有一条消息DoesNotUnderstand,当对象不理解消息时(即当对象未实现发送消息时)调用该消息 所以,我想知道python中是否有一个函数做同样的事情 在本例中: class MyObject: def __init__(self): print "MyObject created" anObject = MyObject() # prints: MyObject created anObject.DoSomething() # rais

在Smalltalk中,有一条消息
DoesNotUnderstand
,当对象不理解消息时(即当对象未实现发送消息时)调用该消息

所以,我想知道python中是否有一个函数做同样的事情

在本例中:

class MyObject:
    def __init__(self):
        print "MyObject created"

anObject = MyObject() # prints: MyObject created
anObject.DoSomething() # raise an Exception
那么,我可以在
MyObject
中添加一个方法,以便知道打算何时调用
DoSomething


PS:对不起,我的英语很差。

您正在寻找
\uu getattr\uu
方法。看一看


如果您想“完全控制”一个类,请查看
\uuuuGetAttribute\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu>特殊方法()。

您查看过对象了吗。
\uuuuuuuuuuuuuuuGetAttr?(请参阅)

以下是您想做的事情:

class callee:
    def __init__(self, name):
        self.name = name

    def __call__(self):
        print self.name, "has been called"


class A:
    def __getattr__(self, attr):
        return callee(attr)

a = A()

a.DoSomething()
>>> DoSomething has been called

我不知道luc为什么要上两门不同的课。如果使用闭包,可以用一个类完成所有操作。像这样:

class A(object):
    __ignored_attributes__ = set(["__str__"])

    def __getattr__(self, name):
        if __name__ in self.__ignored_attributes__:
            return None

        def fn():
            print name, "has been called with self =", self

        return fn

a = A()
a.DoSomething()

我添加了一点关于
\uu忽略属性的内容,因为Python在类中查找
\uu str\uu
,这有点混乱。

这正是我想要的!谢谢:)我喜欢有人公然挑衅!(或者这是“挑战性的确定”?)不管怎样,这样又可以挽救这一天了!:)两个类,因为它可以更容易地重用。假设您希望B类具有相同的行为