Как гнездовать определения типа общего типа? [дублировать]Python

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 Как гнездовать определения типа общего типа? [дублировать]

Сообщение Anonymous »

Скажем, у меня есть:
  • класс a
  • Класс B это Параметризованный типом с верхней границей A
  • класс C , который параметризован типом с верхней границей B .
Как я должен определить эти классы в Python 3.12, так что статические проверки типа наиболее успешны/правильны?
class A:
...

class B[T: A]:
...

class C[T: B]:
...

или я должен использовать C [t1: a, t2: b] ?
Я понял, что c [t: b [t: a]] не разрешен.
отдельный Typevar связан с b [a] работать?
, чтобы сделать его чуть менее абстрактным и показать Использование для этого: < /p>
  • A может быть векторным типом, который я мог бы подтип в качестве вектора 2D или 3D.
  • B может быть геометрической формой, с подтипами, такими как линия и дуга, в 2D, 3D и т. Д. Вкусы.
  • C может быть объединением форм, таким образом, построить из этих 2D/3D Lines/Arcs.
Вот конкретный исполняемый пример: < Br />from typing import Self, Type, cast, reveal_type

# Basic structure:

class Vector:
identity: 'Vector'

class Primitive[V: Vector]:
def __init__(self, b: V, e: V):
self.b, self.e = b, e

class Line[V: Vector](Primitive[V]): pass

class Arc[V: Vector](Primitive[V]):
def __init__(self, b: V, e: V, r: float):
super().__init__(b, e)
self.r = r

class PathSegment[V: Vector](Primitive[V]):
def __init__(self, e: V, previous: Self | None = None):
vector_type = cast(Type[V], e.__class__)
b = previous.e if previous else vector_type.identity
super().__init__(b=b, e=e)

class LineSegment[V: Vector](Line[V], PathSegment[V]): pass
class ArcSegment[V: Vector](Arc[V], PathSegment[V]): pass

class Path[S: PathSegment, V: Vector]:
def __init__(self, segments: list):
self.segments = segments

@property
def b(self) -> V:
return self.segments[0].b

# 2D and 3D variants:

class Vector2D(Vector):
def __init__(self, x: float, y: float):
self.v = (x, y)
Vector2D.identity = Vector2D(0, 0)

class Vector3D(Vector):
def __init__(self, x: float, y: float, z: float):
self.v = (x, y, z)
Vector3D.identity = Vector3D(0, 0, 0)

class Line2D(Line[Vector2D]): pass
class Line3D(Line[Vector3D]): pass
class Arc2D(Arc[Vector2D]): pass
class Arc3D(Arc[Vector3D]): pass
class PathSegment2D(PathSegment[Vector2D]): pass
class PathSegment3D(PathSegment[Vector3D]): pass
class LineSegment2D(LineSegment[Vector2D]): pass
class LineSegment3D(LineSegment[Vector3D]): pass
class ArcSegment2D(ArcSegment[Vector2D]): pass
class ArcSegment3D(ArcSegment[Vector3D]): pass
class Path2D(Path[PathSegment2D, Vector2D], Vector2D): pass
class Path3D(Path[PathSegment3D, Vector3D], Vector3D): pass

p1 = Path2D(segments=[LineSegment2D(e=Vector2D(2, 3))])
# Complaints about this line:
# pycharm: Expected type 'list[PathSegment2D]' (matched generic type 'list[S ≤: PathSegment]'), got 'list[LineSegment2D[Vector2D]]' instead
# pyright: Argument of type "list[LineSegment2D]" cannot be assigned to parameter "segments" of type "list[PathSegment2D]"
# in function "__init__". "LineSegment2D" is not assignable to "PathSegment2D" (reportArgumentType)

# Mix-up of types not detected.
class WrongPathClass(Path[PathSegment2D, Vector3D], Vector2D): pass


Подробнее здесь: https://stackoverflow.com/questions/794 ... efinitions
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • Как гнездовать определения типа общего типа?
    Anonymous » » в форуме Python
    0 Ответы
    12 Просмотры
    Последнее сообщение Anonymous
  • Как гнездовать общие определения типа в Python
    Anonymous » » в форуме Python
    0 Ответы
    10 Просмотры
    Последнее сообщение Anonymous
  • Можете ли вы гнездовать HTML -формы?
    Anonymous » » в форуме Html
    0 Ответы
    3 Просмотры
    Последнее сообщение Anonymous
  • Рекурсив Jekyll включает в себя призыв к ошибке «гнездовать слишком глубокое» при вынесении вложенных комментариев
    Anonymous » » в форуме Html
    0 Ответы
    3 Просмотры
    Последнее сообщение Anonymous
  • Можно ли гнездовать выравнивание для структуры и члена в C ++?
    Anonymous » » в форуме C++
    0 Ответы
    4 Просмотры
    Последнее сообщение Anonymous

Вернуться в «Python»