Issue
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.
Solution
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)
Answered By - crissal
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.