python中的不可编辑对象

2024-10-01 09:24:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图编写一个函数,返回包含在一个类型为Rule的类中的变量。我需要遍历它,获取所有变量并将它们存储在一个集合中

class Rule:
    # head is a function
    # body is a *list* of functions
    def __init__(self, head, body):
        self.head = head
        self.body = body
    def __str__(self):
        return str(self.head) + ' :- ' + str(self.body)
    def __eq__(self, other):
        if not isinstance(other, Rule):
            return NotImplemented
        return self.head == other.head and self.body == other.body
    def __hash__(self):
        return hash(self.head) + hash(self.body)


class RuleBody:
    def __init__(self, terms):
        assert isinstance(terms, list)
        self.terms = terms
    def separator(self):
        return ','
    def __str__(self):
        return '(' + (self.separator() + ' ').join(
            list(map(str, self.terms))) + ')'
    def __eq__(self, other):
        if not isinstance(other, RuleBody):
            return NotImplemented
        return self.terms == other.terms
    def __hash__(self):
        return hash(self.terms)

我的职能如下:

def variables_of_clause (self, c : Rule) -> set :
        returnSet = set()
        l = getattr(c, 'body')
        for o in l:
            returnSet.add(o)

测试功能

# The variables in a Prolog rule p (X, Y, a) :- q (a, b, a) is [X; Y]
def test_variables_of_clause (self):
        c = Rule (Function ("p", [Variable("X"), Variable("Y"), Atom("a")]),
                    RuleBody ([Function ("q", [Atom("a"), Atom("b"), Atom("a")])]))
        #assert
        (self.variables_of_clause(c) == set([Variable("X"), Variable("Y")]))

我一直收到这样一个错误:TypeError:“RuleBody”是不可编辑的


Tags: ofselfreturndefbodyhashvariablesrule
1条回答
网友
1楼 · 发布于 2024-10-01 09:24:23

RuleBody.terms是一个list,而不是RuleBody,您可以在RuleBody.terms上迭代,但是,您可以使用__iter__方法使RuleBody类可编辑(基本上使其返回RuleBody.terms的元素):

class RuleBody:
    ... # everything
    ...
    def __iter__(self):
        return iter(self.terms)

相关问题 更多 >