__name__上的抽象属性未强制执行(Abstract Property on __name__ not enforced)

请考虑以下示例代码:

from abc import ABC, abstractmethod, abstractproperty

class Base(ABC):

    @abstractmethod
    def foo(self) -> str:
        print("abstract")

    @property
    @abstractmethod
    def __name__(self) -> str:
        return "abstract"

    @abstractmethod
    def __str__(self) -> str:
        return "abstract"

    @property
    @abstractmethod
    def __add__(self, other) -> str:
        return "abstract"


class Sub(Base):

    def foo(self):
        print("concrete")

    def __str__(self):
        return "concrete"

    def __add__(self, other) -> str:
        return "concrete"


sub = Sub()
sub.foo()
sub.__name__
print(str(sub))

请注意,子类没有实现抽象属性__name__ ,实际上当引用__name__时,它从父节点打印为“abstract”:

>>> sub.foo()
concrete
>>> sub.__name__
'abstract'
>>> print(str(sub))
concrete

但是,这不是因为__name__是一个dunder方法,也不是因为__name__@abstractmethod装饰器的某些问题不能很好地协同工作,因为如果我从Sub删除__add__的实现,它不会让我实例化它。 (我知道__add__通常不是属性,但我想使用'真正的'dunder方法)如果删除__str__foo的实现,会发生同样的预期行为。 只有__name__这样。

什么是__name__引起这种行为? 有没有办法解决这个问题,或者我是否需要手动为父(抽象)实现引发TypeError


Consider the following sample code:

from abc import ABC, abstractmethod, abstractproperty

class Base(ABC):

    @abstractmethod
    def foo(self) -> str:
        print("abstract")

    @property
    @abstractmethod
    def __name__(self) -> str:
        return "abstract"

    @abstractmethod
    def __str__(self) -> str:
        return "abstract"

    @property
    @abstractmethod
    def __add__(self, other) -> str:
        return "abstract"


class Sub(Base):

    def foo(self):
        print("concrete")

    def __str__(self):
        return "concrete"

    def __add__(self, other) -> str:
        return "concrete"


sub = Sub()
sub.foo()
sub.__name__
print(str(sub))

Note that the subclass does not implement the abstract property __name__, and indeed when __name__ is referenced, it prints as "abstract" from its parent:

>>> sub.foo()
concrete
>>> sub.__name__
'abstract'
>>> print(str(sub))
concrete

However, it is not because __name__ is a dunder method, nor because of some issue with @property and @abstractmethod decorators not working well together, because if I remove the implementation of __add__ from Sub, it does not let me instantiate it. (I know __add__ is not normally a property, but I wanted to use a 'real' dunder method) The same expected behavior occurs if I remove the implementation of __str__ and foo. Only __name__ behaves this way.

What is it about __name__ that causes this behavior? Is there some way around this, or do I need to have the parent (abstract) implementation manually raise the TypeError for me?


原文:https://stackoverflow.com/questions/41173879
2022-04-30 22:04

满意答案

我们来看看生成的字节码:

fun <T> getValue(): T {
    return 1000 as T
}

// becomes

public final getValue()Ljava/lang/Object;
   L0
    LINENUMBER 17 L0
    SIPUSH 1000
    INVOKESTATIC java/lang/Integer.valueOf (I)Ljava/lang/Integer;
    CHECKCAST java/lang/Object
    ARETURN
   L1
    LOCALVARIABLE this LSimpleClass; L0 L1 0
    MAXSTACK = 1
    MAXLOCALS = 1

正如您所看到的,此方法不会将 1000转换为Long它只是确保对象的类型为java/lang/Object (嗯,它是)并返回1000作为Integer对象。

因此,您可以使用任何类型调用(注意:仅调用)此方法,这不会引发异常。 但是,将结果存储在变量中会调用实际强制转换,这可能会导致ClassCastException

fun f3() {
    val simpleObject = SimpleClass()
    // L0
    //   LINENUMBER 16 L0
    //   NEW SimpleClass
    //   DUP
    //   INVOKESPECIAL SimpleClass.<init> ()V
    //   ASTORE 0

    simpleObject.getValue<SimpleClass>() // no problems
    // L1
    //   LINENUMBER 17 L1
    //   ALOAD 0
    //   INVOKEVIRTUAL SimpleClass.getValue ()Ljava/lang/Object;
    //   POP

    val number = simpleObject.getValue<SimpleClass>() // throws ClassCastException1
    // L2
    //   LINENUMBER 18 L2
    //   ALOAD 0
    //   INVOKEVIRTUAL SimpleClass.getValue ()Ljava/lang/Object;
    //   CHECKCAST SimpleClass
    //   ASTORE 1


    // L3
    //   LINENUMBER 19 L3
    //   RETURN
    // L4
    //   LOCALVARIABLE number LSimpleClass; L3 L4 1
    //   LOCALVARIABLE simpleObject LSimpleClass; L1 L4 0
    //   MAXSTACK = 2
    //   MAXLOCALS = 2
}

但为什么将结果存储为Long? 抛出异常? 再说一次,我们来看看字节码的差异:

var number: Long? = null              |    var number: Long = 0
                                      |
      ACONST_NULL                     |        LCONST_0
      CHECKCAST java/lang/Long        |        LSTORE 0                
      ASTORE 0                        |

                number = simpleObject.getValue<Long>() [both]

      ALOAD 1                         |
              INVOKEVIRTUAL SimpleClass.getValue ()Ljava/lang/Object; [both]
      CHECKCAST java/lang/Long        |        CHECKCAST java/lang/Number
      ASTORE 0                        |        INVOKEVIRTUAL java/lang/Number.longValue ()J
                                      |        LSTORE 0

如您所见, number: Long的字节码将函数结果转换为Number ,然后调用Number.longValue以将值转换为Long (Java中的long

但是,数字的字节码number: Long? 将函数结果直接转换为Long? (在Java中很Long )导致ClassCastException

不确定,如果这种行为记录在某处。 但是, as运算符执行不安全的转换,编译器会警告它:

Warning:(21, 16) Kotlin: Unchecked cast: kotlin.Int to T

Let's take a look into generated bytecode:

fun <T> getValue(): T {
    return 1000 as T
}

// becomes

public final getValue()Ljava/lang/Object;
   L0
    LINENUMBER 17 L0
    SIPUSH 1000
    INVOKESTATIC java/lang/Integer.valueOf (I)Ljava/lang/Integer;
    CHECKCAST java/lang/Object
    ARETURN
   L1
    LOCALVARIABLE this LSimpleClass; L0 L1 0
    MAXSTACK = 1
    MAXLOCALS = 1

As you can see, this method does not cast 1000 to a Long it simply ensures, that the object is of type java/lang/Object (well, it is) and returns the 1000 as an Integer object.

Therefore, you may call (note: call only) this method with any type and this will not throw exception. However, storing the result in a variable invokes real cast which may lead to ClassCastException

fun f3() {
    val simpleObject = SimpleClass()
    // L0
    //   LINENUMBER 16 L0
    //   NEW SimpleClass
    //   DUP
    //   INVOKESPECIAL SimpleClass.<init> ()V
    //   ASTORE 0

    simpleObject.getValue<SimpleClass>() // no problems
    // L1
    //   LINENUMBER 17 L1
    //   ALOAD 0
    //   INVOKEVIRTUAL SimpleClass.getValue ()Ljava/lang/Object;
    //   POP

    val number = simpleObject.getValue<SimpleClass>() // throws ClassCastException1
    // L2
    //   LINENUMBER 18 L2
    //   ALOAD 0
    //   INVOKEVIRTUAL SimpleClass.getValue ()Ljava/lang/Object;
    //   CHECKCAST SimpleClass
    //   ASTORE 1


    // L3
    //   LINENUMBER 19 L3
    //   RETURN
    // L4
    //   LOCALVARIABLE number LSimpleClass; L3 L4 1
    //   LOCALVARIABLE simpleObject LSimpleClass; L1 L4 0
    //   MAXSTACK = 2
    //   MAXLOCALS = 2
}

But why storing the result as a Long? throws an exception? Again, let's take a look at the differences in bytecode:

var number: Long? = null              |    var number: Long = 0
                                      |
      ACONST_NULL                     |        LCONST_0
      CHECKCAST java/lang/Long        |        LSTORE 0                
      ASTORE 0                        |

                number = simpleObject.getValue<Long>() [both]

      ALOAD 1                         |
              INVOKEVIRTUAL SimpleClass.getValue ()Ljava/lang/Object; [both]
      CHECKCAST java/lang/Long        |        CHECKCAST java/lang/Number
      ASTORE 0                        |        INVOKEVIRTUAL java/lang/Number.longValue ()J
                                      |        LSTORE 0

As you can see, the bytecode for number: Long casts the function result to a Number and then calls Number.longValue in order to convert the value to a Long (long in Java)

However, the bytecode for number: Long? casts the function result directly into the Long? (Long in Java) which leads to ClassCastException.

Not sure, if this behavior documented somewhere. However, the as operator performs unsafe cast and the compiler warns about it:

Warning:(21, 16) Kotlin: Unchecked cast: kotlin.Int to T

相关问答

更多

JSON在Java中加载:java.lang.ClassCastException:java.lang.Long无法强制转换为java.lang.Integer(JSON Loading in Java: java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer)

当您编写json文件时,所有其他信息都会丢失(在您的情况下是您使用的Integer类型。当您阅读它时,JSONParser会在遇到没有小数点的数字时自动使用Long 。请尝试在阅读器中使用Long 。请注意读者对作者一无所知 。它只能读取文件并按其认为合适的方式解读。 所以回答你的问题: Long age =(Long) ob.get("age"); 将工作。 When you write your json file all additional information is lost (in...

ClassCastException:无法转换为java.lang.Integer(ClassCastException : cant be cast to java.lang.Integer)

private HashMap<Integer, ArrayList<Integer>> edges; // ...later Edge e = new Edge(from,to,T); // ...later else { tmp = new ArrayList(); edges.put(e.from,tmp); } tmp.add(e); 最终,这是原始类型不好的典型例子。 你有一个ArrayList<Integer> ,你将Edge放入其中。 不幸的是,我不知道如...

java.util.ArrayList不能转换为java.lang.Long中的hibernate分离标准(java.util.ArrayList cannot be cast to java.lang.Long hibernate detached criteria)

在匹配集合中的项目时使用Restrictions.in("t.id",taxIds) 。 这里Restrictions.eq("t.id",taxIds) ,taxIds是ArrayList,t.id是Long,所以java.util.ArrayList不能转换为java.lang.Long异常 Use Restrictions.in("t.id",taxIds) while matching an item from a collection. Here Restrictions.eq("t.i...

java.lang.ClassCastException:java.math.BigInteger不能转换为java.lang.Long(java.lang.ClassCastException: java.math.BigInteger cannot be cast to java.lang.Long)

使用BigInteger#longValue()方法,而不是将其转换为Long : return firstResult.get(0).longValue(); 看起来像firstResult.get(0)返回一个Object 。 一种选择是对BigInteger进行类型转换: return ((BigInteger)firstResult.get(0)).longValue(); 但不要这样做。 而应使用Nambari在评论中提供的方式。 我不是Hibernate的用户,所以我不能提供Hib...

java:ClassCastException - [Ljava.lang.Long;(java: ClassCastException - [Ljava.lang.Long; cannot be cast to java.lang.Long)

第一个对象是Long数组,第二个是Long 。 尝试这个 Long l = 1l; Long[] l2 = {}; System.out.println(l.getClass()); System.out.println(l2.getClass()); 产量 class java.lang.Long class [Ljava.lang.Long; 但我确实同意[L_class_; 数组类型的表示非常混乱。 我想知道这是怎么回事。 The first object...

java.lang.Integer不能在Kotlin中强制转换为java.lang.Long(当初始值为null时)(java.lang.Integer cannot be cast to java.lang.Long in Kotlin (when the initial value is null))

我们来看看生成的字节码: fun <T> getValue(): T { return 1000 as T } // becomes public final getValue()Ljava/lang/Object; L0 LINENUMBER 17 L0 SIPUSH 1000 INVOKESTATIC java/lang/Integer.valueOf (I)Ljava/lang/Integer; CHECKCAST java/lang/Obj...

Hibernate HQL转换java.lang.ClassCastException:java.lang.Integer无法强制转换为java.lang.Long(Hibernate HQL casting java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long)

使用set t.done = (t.done=false) ,因此Query将是: update ToDo t set t.done = (t.done=false) where t.id=:id Use set t.done = (t.done=false), so the Query would be: update ToDo t set t.done = (t.done=false) where t.id=:id

例外:java.lang.String无法强制转换为java.lang.Integer(Exception: java.lang.String cannot be cast to java.lang.Integer)

如果存储在密钥runtime值不是Integer类型,那么您将不可避免地遇到此ClassCastException 。 假设电影是Map ,你可以按如下方式重写: String movieRuntime; if (!movies.containsKey("runtime")) { movieRuntime="*Not Available*"; } else if (movies.get("runtime") instanceof Integer){ movieRuntime = S...

serverError:class java.lang.ClassCastException java.lang.Integer无法强制转换为java.lang.String(serverError: class java.lang.ClassCastException java.lang.Integer cannot be cast to java.lang.String)

根据异常,JSF实际上将Integer实例作为value传递给validate()方法。 从技术上讲,您应该将其转换为Integer ,如下所示,以保持Java运行时的快乐。 // Cast the value of the entered input to Integer. Integer input = (Integer) value; 显然你已经将输入字段绑定到模型中的Integer属性,如下所示: <h:inputText value="#{bean.pricing}" /> priv...

Hibernate:java.lang.ClassCastException:java.lang.Integer无法强制转换为java.lang.Double(Hibernate : java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Double)

Hibernate认为它是一个整数,告诉它是双重的。 criteria.add(Restrictions.eq("salary", 1000000d)); Hibernate considering it as a integer, tell that it's double. criteria.add(Restrictions.eq("salary", 1000000d));

相关文章

更多

could not find system property or JNDI

Thanks everyone!! Finally got a solution for this p ...

mybatis There is no getter for property named 'xx' in 'class java.lang.String

用mybatis查询时,传入一个字符串传参数,且进行判断时,会报 There is no get ...

spring+hibernate+mysql执行HQL查询报未打开游标错误

spring配置: &lt;bean id=&quot;dataSource&quot; class ...

研磨设计模式之抽象工厂模式(Abstract Factory)-场景问题

举个生活中常见的例子——组装电脑,我们在组装电脑的时候,通常需要选择一系列的配件,比如:CPU、硬盘、 ...

eclipse+pydev环境下开发python的问题

首先我参阅了许多关于中文问题的例子,但都没人能解决我的问题,苦恼了很久。 关于环境我会一一道来。 ...

页面获取ACTION的属性,页面不能弹出JS

action定义一个属性,get set后 对属性赋值,值是JS,页面用&lt;s:property/ ...

抽象类与接口的区别

abstract class和interface是Java语言中对于抽象类定义进行支持的两种机制,正是 ...

Java 抽象类

Java 抽象类 在面向对象的概念中,所有的对象都是通过类来描绘的,但是反过来,并不是所有 ...

Java:IO/NIO篇,读写属性文件(properties)

1. 描述 尝试用多种方法读取属性文件。 测试打印系统属性; 测试读取、写入用户属性文件; 测试 ...

java强制删除文件

各位,我用File类中的delete()方法删除一个文件夹得到false返回结果 在命令行中用del ...

最新问答

更多

获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)

我用Google搜索了一个解决方案。 “EnumDisplayModeProvider”是我自己设置网站的各种模式的枚举。 public EnumDisplayModeProvider GetDisplayModeId() { foreach (var mode in DisplayModeProvider.Instance.Modes) if (mode.CanHandleContext(HttpContext)) {

如何通过引用返回对象?(How is returning an object by reference possible?)

这相对简单:在类的构造函数中,您可以分配内存,例如使用new 。 如果你制作一个对象的副本,你不是每次都分配新的内存,而是只复制指向原始内存块的指针,同时递增一个也存储在内存中的引用计数器,使得每个副本都是对象可以访问它。 如果引用计数降至零,则销毁对象将减少引用计数并仅释放分配的内存。 您只需要一个自定义复制构造函数和赋值运算符。 这基本上是共享指针的工作方式。 This is relatively easy: In the class' constructor, you allocate m

矩阵如何存储在内存中?(How are matrices stored in memory?)

正如它在“熵编码”中所说的那样,使用Z字形图案,与RLE一起使用,在许多情况下,RLE已经减小了尺寸。 但是,据我所知,DCT本身并没有给出稀疏矩阵。 但它通常会增强矩阵的熵。 这是compressen变得有损的点:输入矩阵用DCT传输,然后量化量化然后使用霍夫曼编码。 As it says in "Entropy coding" a zig-zag pattern is used, together with RLE which will already reduce size for man

每个请求的Java新会话?(Java New Session For Each Request?)

你是如何进行重定向的? 您是否事先调用了HttpServletResponse.encodeRedirectURL()? 在这里阅读javadoc 您可以使用它像response.sendRedirect(response.encodeRedirectURL(path)); The issue was with the path in the JSESSIONID cookie. I still can't figure out why it was being set to the tomca

css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)

我认为word-break ,如果你想在一个单词中打破行,你可以指定它,这样做可以解决问题: .column { word-break:break-all; } jsFiddle演示。 您可以在此处阅读有关word-break属性的更多信息。 I think word-break, with which you can specify if you want to break line within a word, will do the trick: .column { word-break

无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)

我认为您忘记在分类时间内缩放输入图像,如train_test.prototxt文件的第11行所示。 您可能应该在C ++代码中的某个位置乘以该因子,或者使用Caffe图层来缩放输入(请查看ELTWISE或POWER图层)。 编辑: 在评论中进行了一次对话之后,结果发现在classification.cpp文件中错误地删除了图像均值,而在原始训练/测试管道中没有减去图像均值。 I think you have forgotten to scale the input image during cl

xcode语法颜色编码解释?(xcode syntax color coding explained?)

转到: Xcode => Preferences => Fonts & Colors 您将看到每个语法高亮颜色旁边都有一个简短的解释。 Go to: Xcode => Preferences => Fonts & Colors You'll see that each syntax highlighting colour has a brief explanation next to it.

在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)

你考虑过第三方拼写检查吗? 您可以将在C#中开发的自定义WinForms控件插入访问数据库吗? VB6控件怎么样? 如果你能找到一个使用第三方库进行拼写检查的控件,那可能会有效。 Have you considered a third party spell checker? Can you insert a custom WinForms controls developed in C# into an access database? What about a VB6 control? If

从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)

我有同样的问题,因为我在远程服务器上有两个图像,我需要在每天的预定义时间复制到我的本地服务器,这是我能够提出的代码... try { if(@copy('url/to/source/image.ext', 'local/absolute/path/on/server/' . date("d-m-Y") . ".gif")) { } else { $errors = error_get_last(); throw new Exception($err

从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))

我不确定我完全明白你在说什么。 你能编辑你的帖子并包含你正在做的Subversion命令/操作的特定顺序吗? 最好使用命令行svn客户端,以便容易为其他人重现问题。 如果您只是想获取文件的旧副本(即使该文件不再存在),您可以使用如下命令: svn copy ${repo}/trunk/moduleA/file1@${rev} ${repo}/trunk/moduleB/file1 其中${repo}是您的存储库的URL, ${rev}是您想要的文件的版本。 这将恢复该文件的旧版本,包括最高版本