简体   繁体   中英

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

I am fairly new to Python, coming from a Java background. 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 ). 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.

If you're interested in static typing, you can also check 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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