首页 \ 问答 \ 可调用类的不可调用子类(Non-callable subclass of a callable class)

可调用类的不可调用子类(Non-callable subclass of a callable class)

我有一个可以调用的A类。 我还有A名为BA的子类,我想让它不可调用。 当我尝试调用它时,它应该引发正常的“不可调用” TypeError

class A():
    def __call__(self):
        print "I did it"

class B(A):
    def __call__(self):
        raise TypeError("'B' object is not callable")

如您所见,我现在的解决方案是提出正常TypeError的副本。 这感觉不对,因为我只是复制标准python异常的文本。 如果有一种方法可以将子类标记为不可调用,然后让python处理该属性,那将会更好(在我看来)。

使B类不可调用的最佳方法是什么,因为它是可调用类A的子类?


I have a class A that is callable. I also have a subclass of A called B that I want to make not callable. It should raise the normal "not callable" TypeError when I try to call it.

class A():
    def __call__(self):
        print "I did it"

class B(A):
    def __call__(self):
        raise TypeError("'B' object is not callable")

As you can see, my solution right now is to raise a duplicate of the normal TypeError. This feels wrong, since I'm just copying the text of a standard python exception. It would be better (in my opinion) if there was a way to mark a subclass as not callable and then have python handle that attribute.

What is the best way to make class B not callable, given that it's a subclass of the callable class A?


原文:https://stackoverflow.com/questions/17748551
更新时间:2024-02-28 13:02

最满意答案

是否有机会创建用户定义类型的对象,导致重用现有对象?

只有在明确设计用户定义类型的情况下才会发生这种情况。 用__new__()或一些元类。

我想知道我是否可以验证我的任何班级是否会出现这种行为。

使用源代码,卢克。

当涉及到int ,小的整数是预分配的,并且这些预分配的整数用于创建用整数计算的任何位置。 当MyInt(1) is MyInt(1)时,你不能得到这个工作,因为你在那里有没有整数。 然而:

>>> MyInt(1) + MyInt(1) is 2
True

这当然是因为MyInt(1)+ MyInt(1)不返回MyInt。 它返回一个int,因为这就是整数的__add__返回的值(这也是对预分配整数的检查发生的地方)。 如果有的话,这只是表明子类int通常不是特别有用。 :-)

这是否意味着语言为不覆盖新的用户定义类提供“不同的对象保证”,还是仅仅是一个任意的实现行为?

它不保证它,因为没有必要这样做。 默认行为是创建一个新的对象。 如果你不希望发生这种情况,你必须重写它。 有保证是没有道理的。


Is there any chance that the creation of an object of a user-defined type results in a reuse of an existing object?

This will happen if, and only if, the user-defined type is explicitly designed to do that. With __new__() or some metaclass.

I'd like to know how I can verify for any class I work with whether it might exhibit such a behavior.

Use the source, Luke.

When it comes to int, small integers are pre-allocated, and these pre-allocated integers are used wherever you create of calculate with integers. You can't get this working when you do MyInt(1) is MyInt(1), because what you have there are not integers. However:

>>> MyInt(1) + MyInt(1) is 2
True

This is because of course MyInt(1) + MyInt(1) does not return a MyInt. It returns an int, because that's what the __add__ of an integer returns (and that's where the check for pre-allocated integers occur as well). This if anything just shows that subclassing int in general isn't particularly useful. :-)

Does this mean the language provides "distinct object guarantee" for user-defined classes that don't override new, or is it just an arbitrary implementation behavior?

It doesn't guarantee it, because there is no need to do so. The default behavior is to create a new object. You have to override it if you don't want that to happen. Having a guarantee makes no sense.

相关问答

更多
  • 使用$()函数将始终创建一个新对象,因此无论如何,您的相等性检查总是会失败。 例如: var div = document.getElementById('myDiv'); $(div) === $(div); // false! 相反,您可以尝试只存储实际的DOM元素,因为这些元素只是在jQuery对象内引用 。 val = $('#box'+index).get(0); ... if (this !== val) { } Using the $() function will always c ...
  • 功能返回值被认为是临时性的,并且返回值的构造在本地人被破坏之前被排序。 不幸的是,这在标准中不太明确。 有一个开放的缺陷描述这一点,并提供一些措辞来解决这个问题 [...]具有类型为void的操作数的返回语句只能在返回类型为cv void的函数中使用。 任何其他操作数的返回语句只能在返回类型不为cv void的函数中使用; return语句初始化通过copy-initialization(8.5 [dcl.init])从操作数返回的对象或引用。 [...] 在返回实体的操作数建立的完整表达式结束之前破坏临时 ...
  • 是保证返回对象(仅针对新对象),但需要注意一点: 根据AWS文档 : Amazon S3为所有区域的S3存储桶中的新对象的PUTS提供了读写后一致性,但有一点需要注意。 需要注意的是,如果您在创建对象之前对密钥名称发出HEAD或GET请求(以查找对象是否存在),则Amazon S3会为写入后读取提供最终一致性。 Amazon S3提供了在所有区域覆盖PUTS和DELETES的最终一致性。 编辑:@Michael的信用 - sqlbot,更多关于HEAD(或)GET警告: 如果在对象存在之前发送GET或HEA ...
  • 是否有机会创建用户定义类型的对象,导致重用现有对象? 只有在明确设计用户定义类型的情况下才会发生这种情况。 用__new__()或一些元类。 我想知道我是否可以验证我的任何班级是否会出现这种行为。 使用源代码,卢克。 当涉及到int ,小的整数是预分配的,并且这些预分配的整数用于创建用整数计算的任何位置。 当MyInt(1) is MyInt(1)时,你不能得到这个工作,因为你在那里有没有整数。 然而: >>> MyInt(1) + MyInt(1) is 2 True 这当然是因为MyInt(1)+ M ...
  • 根据标准,程序可以打印0,1或2.C ++ 11中的特定段落是12.8p31,以: 当满足某些条件时,允许实现省略类对象的复制/移动构造,即使对象的复制/移动构造函数和/或析构函数具有副作用。 请注意,两个复制精简都不是属于as-if规则的优化(这要求程序的行为与同一程序的行为一致- 如果没有进行优化)。 标准明确允许实现生成不同的可观察行为,程序员可以让您的程序不依赖于此(或接受所有三种可能的结果)。 注2:1在任何答案中都没有提到,但这是一个可能的结果。 有两个可能的副本发生,从函数中的局部变量到返回的 ...
  • 在id(300)被执行后,不再有对300引用,所以id被释放。 当你执行id(6) ,它会得到相同的内存块,并存储6个内存。 当-300 is 6 , -300和6同时被引用,所以它们不再具有相同的地址。 如果您保持对-300和6引用,则会发生这种情况: >>> a, b = -300, 6 >>> id(a) some number >>> id(b) some different number; 6 is still in the other memory address. 注意:在CPython中, ...
  • 当您调用SaveChanges时,身份字段将填充到原始实体上。 因此,要获取此ID,只需存储对该身份的引用并在SaveChanges后访问它: context = new MyContext(); List addedABCs = new List(); List addedXYZs = new List(); foreach (var x in lstX) { var abc = new abc{ name= x.abcName }; addedA ...
  • 整个Realm和所有相关对象都是原子级的,并且不应该观察到不一致的状态。 在通知块中,所有Realm对象和Results将反映通知所针对的新版本。 唯一需要注意的是,显然无法同时调用多个通知块,因此如果您同时allPeople了allPeople和adults通知,则您无法依赖已经完成其他操作的其他通知。 The entire Realm and all associated objects are advanced atomically, and it should not be possible to ...
  • 我读了一些关于对VS ipairs没有返回固定结果顺序的东西 ipairs是表的数组元素的迭代器,按ipairs 顺序排列 。 “数组元素”被定义为表的成员,其键是[1, #tbl]范围内的数值,其中#tbl是应用于表的长度运算符。 pairs是表的所有元素的迭代器:数组和非数组元素。 表的非数组元素没有Lua的内在顺序,因此pairs将以任何顺序返回它们。 即使数组元素在技术上确实有一个订单,但是pairs它们不会例外; 它总是以任意顺序运作。 您的代码就像ipairs一样: ipairs每个数字键,从1 ...
  • 之前提出过非常相似的问题 。 您可以在INSERT指定ORDER BY 。 如果这样做,则生成IDENTITY值的顺序保证与INSERT指定的ORDER BY匹配。 使用你的例子: DECLARE @blah TABLE ( ID INT IDENTITY(1, 1) NOT NULL, Name VARCHAR(100) NOT NULL ); INSERT INTO @blah (Name) SELECT T.Name FROM ( VALUES ...

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。