简体   繁体   English

如何为 Python 变量显式指定 class 类型?

[英]How can I explicitly specify a class type for a Python variable?

I am fairly new to Python, coming from a Java background.我对 Python 相当陌生,来自 Java 背景。 I have something like this:我有这样的事情:

class A:
    def __init__(self):
        self.var1 = 1
        self.var2 = 2

class B:
    def __init__(self):
        self.my_list = []

    def add(self, a_object):
        self.my_list.append(a_object)

    def show(self):
        for a_object in self.my_list:
            print(a_object.var1, a_object.var2)

Now, I know this code will run but my question is if there is any way to specify in the show method that the a_object variable is actually an object of type A (like a type casting - something that I would write in java like (A)a_object ).现在,我知道这段代码会运行,但我的问题是是否有任何方法可以在show方法中指定a_object变量实际上是 A 类型的 object (就像类型转换 - 我会在 java 中写的东西,比如(A)a_object )。 I would want this firstly for a better readeability of the code and also for autocompletion.我首先希望这是为了更好地阅读代码以及自动完成。 I would guess that another solution would be to type the list, which I am also curios if it is possible.我猜另一种解决方案是键入列表,如果可能的话,我也是古玩。

Thank you.谢谢你。

You can use type hinting.您可以使用类型提示。 Note, however, that this is not enforced, but guides you - and the IDE - into knowing if you're passing correct arguments or not.但是请注意,这不是强制执行的,而是引导您 - 以及 IDE - 了解您是否传递了正确的 arguments。

If you're interested in static typing, you can also check mypy .如果您对 static 打字感兴趣,您也可以查看mypy

from typing import List


class A:
    def __init__(self):
        self.var1 = 1
        self.var2 = 2

class B:
    def __init__(self):
        self.my_list: List[A] = []

    def add(self, a_object: A):
        self.my_list.append(a_object)

    def show(self):
        for a_object in self.my_list:
            print(a_object.var1, a_object.var2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM