相关疑难解决方法(0)

如何在Python中继承str

我试图继承str对象,并添加几个方法.我的主要目的是学习如何做到这一点.我被困在哪里,我是否应该在元类中继承字符串,并使用该元或子类str直接创建我的类?

而且,我想我需要以__new__()某种方式实现,因为,我的自定义方法将修改我的字符串对象,并将返回新的mystr obj.

我的类的方法应该可以使用str方法完全链接,并且应该在自定义方法修改它时始终返回一个新的我的类实例.我希望能够做到这样的事情:

a = mystr("something")
b = a.lower().mycustommethod().myothercustommethod().capitalize()
issubclass(b,mystr) # True
Run Code Online (Sandbox Code Playgroud)

我希望拥有它拥有的所有能力str.例如,a = mystr("something")然后我想使用它,如a.capitalize().mycustommethod().lower()

我的理解是,我需要实施__new__().我想是这样的,因为,字符串方法可能会尝试创建新的str实例.所以,如果我覆盖__new__(),他们应该会返回我的自定义str类.但是,__init__()在这种情况下,我不知道如何将参数传递给我的自定义类的方法.我想我需要使用type()才能在__new__()方法中创建一个新实例吗?

python fluent-interface subclassing

26
推荐指数
4
解决办法
2万
查看次数

如何在冻结的数据类自定义 __init__ 方法中设置属性?

我正在尝试构建一个@dataclass定义架构但实际上并未使用给定成员实例化的模型。(基本上,我@dataclass为了其他目的劫持了方便的语法)。这几乎就是我想要的:

@dataclass(frozen=True, init=False)
class Tricky:
    thing1: int
    thing2: str

    def __init__(self, thing3):
        self.thing3 = thing3
Run Code Online (Sandbox Code Playgroud)

但是我FrozenInstanceError__init__方法中得到了一个:

dataclasses.FrozenInstanceError: cannot assign to field 'thing3'
Run Code Online (Sandbox Code Playgroud)

我需要frozen=True(为了哈希)。有什么方法可以在__init__冻结上设置自定义属性@dataclass吗?

python python-3.x python-3.7 python-dataclasses

11
推荐指数
4
解决办法
7866
查看次数

如何在 Python 数据类中使用 __post_init__ 方法

我正在尝试使用Python中的数据类,我想做的是在我的类中拥有一个计算字段,并将 sort_index 字段添加到调用中,但也希望将其冻结,以便我无法修改任何属性定义后的此类。下面是我的代码:

from dataclasses import dataclass, field

def _get_year_of_birth(age: int, current_year: int=2019):
    return current_year - age

@dataclass(order=True, frozen=True)
class Person():
    sort_index: int = field(init=False, repr=False)
    name: str
    lastname: str
    age: int
    birthyear: int = field(init=False)


    def __post_init__(self):
        self.sort_index = self.age
        self.birthyear = _get_year_of_birth(self.age)



if __name__ == "__main__":
    persons = [
    Person(name="Jack", lastname="Ryan", age=35),
    Person(name="Jason", lastname="Bourne", age=45),
    Person(name="James", lastname="Bond", age=60)
    ]

    sorted_persons = sorted(persons)
    for person in sorted_persons:
        print(f"{person.name} and {person.age} and year of birth is : {person.birthyear}")
Run Code Online (Sandbox Code Playgroud)

看来我无法在类中设置自定义排序字段,也无法创建从其他属性计算得出的任何属性,因为我使用的是 freeze …

python-3.7 python-dataclasses

9
推荐指数
1
解决办法
2万
查看次数