简体   繁体   English

为类方法分配属性

[英]Assigning attributes to class methods

Suppose I have a class that acts as a method container.假设我有一个充当方法容器的类。 I have a config file that lists those methods in a dictionary.我有一个配置文件,在字典中列出了这些方法。 In a program, I want to import the dictionary from config and iterate over it, calling methods from that class as I go.在一个程序中,我想从 config 导入字典并对其进行迭代,同时从该类调用方法。

The issue is that I need to have them be handled one way if the method is of one kind, and another way if another.问题是,如果方法是一种,我需要以一种方式处理它们,如果是另一种方法,则需要以另一种方式处理。 So the container class looks like:所以容器类看起来像:

class Circus(object):
    def clown(self):
        return print("*HONK*")

    def lion(self):
        return print("roar")

    def __call__(self):
        setattr(clown, 'isFunny', True)
        setattr(lion, 'isFunny', False)

My config file:我的配置文件:

circus = {
    'funny_thing': Circus.clown,
    'unfunny_thing': Circus.lion
}

And the actual script:和实际的脚本:

for item in circus.items():
    if item[1].isFunny == True:
        item()

I've lost track of everything I've tried, but it's included separating this into two classes and creating an isFunny() method in each (returning true or false), assigning things to the class __dict__, placing setattr() in different places, using __init__, @staticmethod and @classmethod .我已经忘记了我尝试过的一切,但它包括将它分成两个类并在每个类中创建一个 isFunny() 方法(返回 true 或 false),将东西分配给 __dict__ 类,将setattr()放在不同的地方,使用 __init__、 @staticmethod@classmethod

What I expect is a simple *HONK* , but most everything spits out an AttributeError: 'function' object has no attribute 'isFunny' .我期望的是一个简单的*HONK* ,但大多数东西都会吐出一个AttributeError: 'function' object has no attribute 'isFunny'

What am I doing wrong?我究竟做错了什么?


For reference, a handful of the links I've tried:作为参考,我尝试过的一些链接:

__call__ is invoked when you call an instance. __call__在您调用实例时被调用。 Given c = Circus() , c() is the same as c.__call__() .鉴于c = Circus()c()c.__call__() As a result, you are trying to check the attribute before it gets defined.因此,您试图在定义之前检查属性。 Further, inside the __call__ method, neither clown nor lion have been defined.此外,在__call__方法中,还没有定义clownlion They are both class attributes, and need to be used as such (ie, either Circus.clown or self.clown ).它们都是类属性,需要按原样使用(即Circus.clownself.clown )。 If you want to tag the methods, just do so directly in the class statement.如果要标记方法,只需直接在class语句中进行即可。

class Circus:
    def clown(self):
        print("*HONK*")

    def lion(self):
        print("roar")

    clown.isFunny = True
    lion.isFunny = False

circus = {
    'funny_thing': Circus.clown,
    'unfunny_thing': Circus.lion
}


for item in circus.items():
    if item[1].isFunny:
        item[1]()

However, note that item[1]() is still wrong, because the unbound method still expects an instance of Circus as its first argument.但是,请注意item[1]()仍然是错误的,因为未绑定的方法仍然需要一个Circus实例作为它的第一个参数。 Some suggested fixes, depending on what you are actually trying to accomplish:一些建议的修复,取决于您实际尝试完成的内容:

  1. Make the methods class methods or static methods, so that no additional arguments are needed.使方法类方法或静态方法,以便不需要额外的参数。

  2. Store bound methods in the dict:在字典中存储绑定方法:

     c = Circus() circus = { 'funny_thing': c.clown, 'unfunny_thing': c.lion }

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

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