简体   繁体   English

用 Python 装饰一个类,打印装饰类的 int 变量

[英]Decorate a class with Python that prints the int variables of the decorated class

I'm studying for a python course and one of the exercise was to create a decorator for this class that returns every int variables.`我正在学习 Python 课程,其中一项练习是为此类创建一个装饰器,该装饰器返回每个 int 变量。`

@decoratoreDiClasse
class MyClass:
    def __init__(self):
        self.a = 1
        self.b = 2
        self.c = 'w'`

My problem is that the list is always empty beacuse dict does not return the variables inside init,how can i solve my problem?我的问题是列表总是空的,因为 dict 不返回 init 中的变量,我该如何解决我的问题? i've written my decorator below我在下面写了我的装饰器

def decoratoreDiClasse(cls):
def elencaVariabili():

    lista = []
    print(cls)
    lista1 = cls.__dict__
    print(lista1)

    for ab in lista1:

        if isinstance(ab, int):
            lista.append(ab)
    return lista

setattr(cls, "elencaVariabili", elencaVariabili())
return cls

here's the part of the main that should print the variables,I cannot change anything apart from "decoratoreDiClasse" due to the teacher request.这是应该打印变量的主要部分,由于老师的要求,除了“decoratoreDiClasse”之外,我无法更改任何内容。

    for v in x.elencaVariabili():
    print(v, end=' ')

It looks like you're supposed to have your decorator add a method to the class that prints out integer-valued attributes on an instance it's called on.看起来你应该让你的装饰器向类添加一个方法,该方法在它被调用的实例上打印出整数值属性。 That's not what you're currently trying to do, as your code tries to find the variables on the class instead of on an instance later on.这不是您当前想要做的,因为您的代码稍后会尝试在类上而不是在实例上查找变量。

Think of what you're doing as a method, and it will be a lot simpler:把你正在做的事情想象成一种方法,它会简单得多:

def decoratoreDiClasse(cls):
    def elencaVariabili(self):     # this is a method, so it should take self!
        lista = [value for value in self.__dict__.values()  # loop over our attribute values
                       if isinstance(value, int)]           # and pick out the integers!
        return lista

    setattr(cls, "elencaVariabili", elencaVariabili)  # don't call the method here
    return cls

It's not entirely clear from your code if you're supposed to be returning the names of the integer variables or just the values themselves.从您的代码中并不完全清楚您是应该返回整数变量的名称还是仅返回值本身。 I went with just the values, but if you need the variable names, you may need to change the list comprehension to iterate over the items() of the instance's dictionary rather than just the values() .我只使用了值,但是如果您需要变量名称,您可能需要更改列表理解以迭代实例字典的items()而不仅仅是values()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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