Advertisement
go6odn28

typing_example

Jun 29th, 2024
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.87 KB | None | 0 0
  1. from typing import List
  2.  
  3.  
  4. class Food:
  5.     def __init__(self, food_name: str):
  6.         self.name = food_name
  7.  
  8.  
  9. class Person:
  10.     def __init__(self, name: str, age: int):
  11.         self.name = name
  12.         self.age = age
  13.         self.some_list: list = []  # вариант без тайпинг
  14.         self.foods: List[Food] = []  # с вариант с тайпинг - по експлицитно,
  15.                                      # в по-старите версии на пайтън мисля, че не се поддържа (но да не те излъжа)
  16.  
  17.  
  18. food1 = Food("Apple")
  19. food2 = Food("Banana")
  20.  
  21. person = Person("Ivan", 30)
  22. person.foods.append(food1)
  23. person.foods.append(food2)
  24.  
  25.  
  26. print(person.name)  # Outputs: Ivan
  27. print(person.age)   # Outputs: 30
  28. print(person.foods[0].name)  # Outputs: Apple
  29. print(person.foods[1].name)  # Outputs: Banana
  30.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement