Is it possible to reference multiple vars defined within a class by classmethod (or by some other means)?
For context I'm trying to consolidate the CRUD and model classes for a SQL database to simplify the codebase.
For example I'm looking to implement something like the below:
from __future__ import annotations
class Person:
name: str
gender: str
age: int
@classmethod
def get_person(cls, db: Session) -> list[Person]:
return db.query(cls.Person) # <-- Key part is here. I'll need to send name,
# gender, and age to the database. Currently
# this is implemented separately as
# `class CrudPerson` and `class ModelPerson`.
CodePudding user response:
Adding from __future__ import annotations
and referencing the class directly seems to work. (e.g. db.query(Person)
)
Additional information on this can be found in PEP 563
CodePudding user response:
If you make Person
a NamedTuple
, you can use cls._fields
.
Or if you make Person
a dataclass
, you can use dataclasses.fields(cls)
.