简体   繁体   English

Python 带列表的数据类

[英]Python dataclass with list

So just learnng Python 3.7 and I want to create a simple dataclass with two data members, an int and a list somethng like:所以只要学习 Python 3.7,我想创建一个简单的数据类,它有两个数据成员,一个 int 和一个列表,比如:

class myobject:
      data1:int
      data2:List[]

object1=myobject(1, 1)
myobject.data2.append(5)
etc...

I tried quite a few things but apparently the List is seen as an integer only not a list and I don't know what to do, can somebody helping me please?我尝试了很多事情,但显然该列表被视为 integer 而不是列表,我不知道该怎么做,有人可以帮助我吗?

cheers干杯

As noted in comments, the type hints are not enforced by Python. If you pass an int where you specified a list, you will get an int.如注释中所述,Python 不强制执行类型提示。如果您在指定列表的地方传递一个 int,您将得到一个 int。

You are also creating an object of the myobject class, but then not using it.您还创建了 myobject class 的myobject ,但随后未使用它。 I think you want something like:我想你想要这样的东西:

from dataclasses import dataclass

@dataclass
class myobject:
    data1: int
    data2: list

object1 = myobject(1, [1])
object1.data2.append(5)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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