简体   繁体   中英

How can I pass the current class to a static method call in Python?

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)

Ugly work around ... but seems to work:

from h_database_orm.domain.entity import Entity

class Human(Entity):   
    first_name = Entity.string()

Human.last_name = Entity.string()  

Human.spouse_id = Entity.foreign_key(Human)
Human.spouse = Entity.one_to_one_attribute(Human)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM