Swift-如何为我的类定义一个特殊方法,该方法返回其对象的字符串表示形式

问题描述 投票:0回答:1

在python中,如果要定义对象的字符串表示形式,则可以执行以下操作:

class Person:

    def __init__(self, first, last, age):
        self.first = first
        self.last = last
        self.age = age

    def __str__(self):
        return f'{self.first} {self.last}, {self.age} years old'

person_1 = Person('John', 'Smith', 25)

现在,如果您输入print(person_1)str(person_1),则会得到John Smith, 25 years old

如果__str__方法不存在,则输出为<__main__.Person object at 0x104e12e20>

我如何迅速做同样的事情?] >>

当然,我可以定义一个我想要的名称的方法,然后在对象上调用它,但是它缺少语法糖。

在python中,如果要定义对象的字符串表示形式,则可以执行以下操作:类Person:def __init __(self,first,last,age):self.first = first self.last = ...

python swift syntactic-sugar
1个回答
0
投票

仅符合CustomStringConvertible协议。您要做的就是实现description属性。

© www.soinside.com 2019 - 2024. All rights reserved.