【问题标题】:General syntax python question : from typed language to untyped one一般语法python问题:从类型语言到非类型语言
【发布时间】:2021-11-16 05:22:44
【问题描述】:

我是 python 语言的新手。 而且我的问题肯定是一个幼稚的问题,并且涉及 python 语法。

我正处于从理论到实践的阶段。

这是一个我想翻译成 python 语言的类(一个打字稿)。

class Category {
    id: number;
    type: 'shop'|'blog';
    name: string;
    slug: string;
    path: string;
    image: string|null;
    items: number;
    customFields: CustomFields;
    parents?: Category[]|null;
    children?: Category[]|null;
}

由于 python 是无类型语言,我对如何翻译有疑问:

  • 可选属性:'?'
  • 关联类:customFields: CustomFields;
  • 关联类(自关联)和可为空的数组:children?: Category[]|null;

到目前为止,我一直在使用类型化语言,而什么都不写会破坏我的习惯。

会是这样吗(它是 django.db 迁移的模型):

>from django.db import models

    >>class Category(models.Model):
    >>>    id = models.AutoField(primary_key=True)
    >>>   type: 'shop'|'blog'
    >>>    name = models.CharField(max_length=100)
    >>>    slug = models.CharField(max_length=100)
    >>>    path = models.CharField(max_length=250)

然后……?

您能否提供一些教程、文档、示例,让您在实践中学习python? 谢谢大家!

【问题讨论】:

  • TypeScript 是 ECMAScript 的正确超集。您可以直接删除所有类型,然后在 ECMAScript(一种动态类型语言)中拥有完全相同的内容。

标签: python typescript model definition


【解决方案1】:

如果您必须强制输入 Python 代码,请输入 look at isinstance
对于 Python 中的可选 Class 属性,您可以使用关键字参数为 shown in this answer

【讨论】:

    【解决方案2】:

    最好按照文档来学习语言,文档中有足够的示例。 https://docs.python.org/3/

    如果你想学习 Django,这里有很多教程。但首先,看这里。 https://docs.djangoproject.com/en/3.2/

    至于您的 Category Class 示例 id是自动确定的,不需要在模型中显式指定,更多见https://docs.djangoproject.com/en/3.2/topics/db/models/

    【讨论】:

    • 谢谢!!!! (尤其是最后一个链接)。它看起来比我所期待的要多得多。 (类似于 codeFirst/entityframework 之类的字段定义。
    • 没问题,祝你好运! @Rémi Duplan
    【解决方案3】:

    当您在 Python 中定义函数时,您可以强制执行静态类型,但这不是必需的。如果您需要强制执行静态类型,您可以执行以下操作。

    //for functions
    def addition(a: int, b: int) -> int:
        return a + b
    addition(4,10)
    
    //For Variables or attributes
    name: str = 'test'
    age: int = 10
    rating: float = 1.11
    is_exist: bool = True
    

    在 python 文档中发现了更多与输入有关的内容以防万一 你可以参考documentation

    【讨论】:

      猜你喜欢
      • 2018-11-12
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 2013-02-03
      • 2018-08-05
      • 2011-02-11
      • 1970-01-01
      • 2016-09-26
      相关资源
      最近更新 更多