[英]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". 如果我在定义该类的静态属性时尝试将类“Human”传递给方法,则会收到错误“Undefined variable:Human”。
=>How can I access the current class (-name) to pass it to the shown method? =>如何访问当前类(-name)以将其传递给显示的方法?
(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? ) (在第7行中没有类Human的实例。因此,这与获取实例的类名不同? )
I could pass the class name as hard coded string "Human" but I would like to avoid hard coded strings if possible. 我可以将类名称作为硬编码字符串“Human”传递,但我想尽可能避免使用硬编码字符串。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.