[英]How to define a new type()
class Something:
def __init__(self, x, y=0):
self.x = x
self.y = y
x is a string and y is a currency number. x是字符串,y是货币数字。 How can i define a new type such that 我如何定义这样的新类型
type(self.y) == Currency
Define a Currency
class like this: 定义一个Currency
类,如下所示:
class Currency(object):
def __init__(self, value):
self.value = value
Then you can create a new variable of type Currency
like this: 然后,您可以创建一个类型为Currency
的新变量,如下所示:
y = Currency(3)
For simple classes(no logic, only data), you can also use dataclasses
. 对于简单的类(没有逻辑,只有数据),您也可以使用dataclasses
。 This is available in python 3.7 这在python 3.7中可用
from dataclasses import dataclass
@dataclass
class Currency:
value: int
For older versions, you can use namedtuple
对于较旧的版本,可以使用namedtuple
from collections import namedtuple
Currency = namedtuple('Currency', ['value'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.