gpt4 book ai didi

kotlin - 类什么时​​候是数据类?

转载 作者:行者123 更新时间:2023-12-05 01:53:56 24 4
gpt4 key购买 nike

我知道类是关于什么的,但为了更好地理解我需要一个用例。最近我发现了数据类的构造。我了解普通类背后的想法,但我无法想象数据类的真实用例。

什么时候应该使用数据类,什么时候使用“普通”类?据我所知,所有类都保存数据。

您能提供一个很好的例子来区分数据类和非数据类吗?

最佳答案

数据类 用于存储数据。它比普通类更轻巧,可以与具有键/值(字典、哈希等)的数组进行比较,但表示为具有固定属性的对象。根据文档,在 Kotlin 中,将这些属性添加到类中:

equals()/hashCode() pair

toString() of the form "User(name=John, age=42)"

componentN() functions corresponding to the properties in their order of declaration.

copy() function

它在类继承期间也有不同的行为:

If there are explicit implementations of equals(), hashCode(), or toString() in the data class body or final implementations in asuperclass, then these functions are not generated, and the existingimplementations are used.

If a supertype has componentN() functions that are open and return compatible types, the corresponding functions are generated for thedata class and override those of the supertype. If the functions ofthe supertype cannot be overridden due to incompatible signatures ordue to their being final, an error is reported.

Providing explicit implementations for the componentN() and copy() functions is not allowed.

所以在 kotlin 中,如果你想描述一个对象(数据)那么你可以使用数据类,但是如果你正在创建一个复杂的应用程序并且你的类需要在构造函数中具有特殊的行为,具有继承或抽象, 那么你应该使用一个普通的类。


我不懂 Kotlin,但在 Python 中,数据类可以看作是结构化的字典。当您想使用字典来存储始终具有相同属性的对象时,您不应将其放在 dict 中,而应使用 Dataclass

普通类的优点是您不需要声明 __init__ 方法,因为它是“自动”(继承的)。

示例:

这是一个普通的类

class Apple:
def __init__(size:int, color:str, sweet:bool=True):
self.size = size
self.color = color
self.sweet = sweet

dataclass 相同的类

from dataclasses import dataclass

@dataclass
class Apple:
size: int
color: str
sweet: bool = True

那么与dict相比的优势就是你确定它有什么属性。它还可以包含方法。

与普通类相比的优点是声明更简单,代码更轻便。我们可以看到属性关键字(例如 size)在普通类中重复了 3 次,但在 dataclass 中只出现了一次。

普通类的优点还在于你可以个性化 __init__ 方法,(也在数据类中,但我认为你失去了它的主要优势)示例:

# You need only 2 variable to initialize your class
class Apple:
def __init__(size:int, color:str):
self.size = size
self.color = color
# But you get much more info from those two.
self.sweet = True if color == 'red' else False
self.weight = self.__compute_weight()
self.price = self.weight * PRICE_PER_GRAM

def __compute_weight(self):
# ...
return (self.size**2)*10 # That's a random example

关于kotlin - 类什么时​​候是数据类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70914225/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com