Python3等同于Java缩小转换

问题描述 投票:0回答:1

我正在使用Python3和PyQt5开发应用程序,其UI布局开始在Qt .ui文件中定义,并在运行时加载到我的QDialog类中。因此,在加载UI时,会自动将我的UI元素的实例(例如QPushButton)分配为我的QDialog类的实例变量。

问题是当我去使用这些变量来修改元素时,我没有得到任何类型的Intellisense类型提示或自动补全,因为Python和我的IDE不知道对象的类是什么。

在Java中,您可以使用显式窄化强制转换将对象强制转换为正确的类型,这时intellisense可以开始提供自动补全功能,因为它知道类型。

例如,在Java和Android SDK中:

TextView name = (TextView) findViewById(R.id.name); 

在此示例中,findViewById返回一个View,因此您可以使用类型转换来确保将其转换为TextView。


在Python中,我想做同样的事情,既要确保我要访问的UI元素是正确的类型,又要能够对实例方法使用自动完成功能。

这是我目前的情况:

""" 
Because Python doesn't know whether self.my_push_button is an instance 
of QPushButton, this may or may not work, but it won't know until runtime, 
so no autocompletion.
"""
self.my_push_button.setEnabled(False) 

我想做的是这样的:

( (QPushButton) self.my_push_button ).setEnabled(False) 

我尝试过:

QPushButton(self.my_push_button).setEnabled(False)

但是据我所知,它会复制原始对象并在新对象上执行setEnabled,这显然不是我想要的。

我也尝试通过isinstance函数使用assert语句:

assert isinstance(self.my_push_button, QPushButton)

"""
This works for providing the code completion and checking the type.
However, it only works within the scope of the assert statement, so adding an assert for each variable in each scope in which it is used would be unnecessarily verbose.
"""
self.my_push_button.setEnabled(False) 

[我知道在Python中没有真正的对象“投射”,但是有什么方法能够在Python中实现类似于缩小铸件的功能,如上所示,在Java中?

我正在使用Python3和PyQt5开发应用程序,其UI布局开始在Qt .ui文件中定义,并在运行时加载到我的QDialog类中。因此,我的UI元素的实例,例如...

python python-3.x
1个回答
0
投票

代码完成不像uic那样对动态生成的元素起作用。

© www.soinside.com 2019 - 2024. All rights reserved.