[英]How can I pass the current class to a static method call in Python?
如果我在定義該類的靜態屬性時嘗試將類“Human”傳遞給方法,則會收到錯誤“Undefined variable:Human”。
=>如何訪問當前類(-name)以將其傳遞給顯示的方法?
(在第7行中沒有類Human的實例。因此,這與獲取實例的類名不同? )
我可以將類名稱作為硬編碼字符串“Human”傳遞,但我想盡可能避免使用硬編碼字符串。
截圖:
人類:
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)
父類實體:
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)
丑陋的工作...但似乎工作:
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.