【问题标题】:How can I pass the current class to a static method call in Python?如何将当前类传递给 Python 中的静态方法调用?
【发布时间】:2019-06-12 13:06:24
【问题描述】:

如果我在定义该类的静态属性时尝试将类“Human”传递给方法,则会收到错误“未定义变量:Human”。

=>如何访问当前类 (-name) 以将其传递给显示的方法?

(在第 7 行中没有 Human 类的实例可用。因此,这是一个与 Getting the class name of an instance? 不同的问题)

我可以将类名作为硬编码字符串“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)

【问题讨论】:

  • 不能把staticmethod改成classmethod吗?对于调用者来说应该没有区别。
  • 我想用第 7 行定义一个静态属性“spouse_id”。是否可以在类方法中定义该静态属性?
  • 嗯,可能不会,它很可能仍会引用 Entity 而不是 Human。 AFAIK,这样的类不能从它自己的类属性中访问,因为它“还不存在”。

标签: python class static


【解决方案1】:

丑陋的解决方法......但似乎有效:

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)

【讨论】:

    猜你喜欢
    • 2018-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-23
    • 1970-01-01
    • 2019-08-11
    相关资源
    最近更新 更多