If I try to pass a class "Human" to a method while defining the static attributes of that class, I get the error "Undefined variable: Human".
=>How can I access the current class (-name) to pass it to the shown method?
(In line 7 there is no instance of the class Human available. Therefore this is a different question than Getting the class name of an instance?)
I could pass the class name as hard coded string "Human" but I would like to avoid hard coded strings if possible.
Screenshot:
Human class:
from h_database_orm.domain.entity import Entity
class Human(Entity):
first_name = Entity.string()
last_name = Entity.string()
spouse_id = Entity.foreign_key(Human)
spouse = Entity.one_to_one_attribute(Human)
Parent class Entity:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy import Column, Integer, Float, String, ForeignKey
from sqlalchemy.orm import relation
class AbstractEntity():
@declared_attr
def __tablename__(self):
return AbstractEntity.table_name_for_class(self)
id = Column(Integer, primary_key=True)
@staticmethod
def table_name_for_class(clazz):
return clazz.__name__.lower()
@staticmethod
def integer():
return Column(Integer)
@staticmethod
def float():
return Column(Float)
@staticmethod
def string():
return Column(String)
@staticmethod
def foreign_key(referencedClass):
table_name = AbstractEntity.table_name_for_class(referencedClass)
foreign_key_path = table_name + '.id'
return Column(Integer, ForeignKey(foreign_key_path))
@staticmethod
def one_to_one_attribute(referenced_class):
class_name = referenced_class.__name__
return relation(class_name, uselist=False)
Entity = declarative_base(cls=AbstractEntity)