社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

有没有办法让Python列表需要特定的对象?

Johan Jarvi • 5 年前 • 1541 次点击  

我在互联网上到处搜索,但我无法找到一种方法来创建一个需要特定对象的Python列表。

我想达到的目标可以用C#来描述: new List<MyObject>()

现在我想不出用Python实现这一点的任何方法。

我试图定义一类潮汐信息:

from models.tideTime import TideTime


class Tides:
    def __init__(self, currentTide: str, movement: str, tideTimes: list):
        self.currentTide = currentTide
        self.movement = movement
        self.tideTimes = tideTimes

在有问题的列表中应该有一个“TideTime”对象的列表,而不仅仅是任何普通的列表。其中,这个TideTime对象是在models目录中定义的另一个类:

class TideTime:
    def __init__(self, time: str, height: str):
        self.time = time
        self.height = height

有人知道怎么做吗?

我知道这并不重要,因为在一天结束的时候,我仍然可以用另一边的TideTime对象列表调用它,但是为了干净的代码和长寿命,我想确保这个对象的列表输入始终是正确的类型,而不是 str 突然之间。

任何帮助都将不胜感激。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/53650
 
1541 次点击  
文章 [ 1 ]  |  最新文章 5 年前
chepner
Reply   •   1 楼
chepner    5 年前

你在找类型提示 List[TideTime] ,其中 List typing 模块。

from typing import List
from models import TideTime

class Tides:
    def __init__(self, currentTide: str, movement: str, tideTimes: List[TideTime]):
        self.currentTide = currentTide
        self.movement = movement
        self.tideTimes = tideTimes

mypy 如果您试图在源代码中传递其他内容,则可以帮助捕获。如果没有别的,更准确的提示更好地记录 意图