English 中文(简体)
python类属性没有设置?
原标题:python class attributes not setting?
  • 时间:2010-10-31 03:35:46
  •  标签:
  • python

我在写一个支持插件扩展的聊天机器人时遇到了一个奇怪的问题。基本扩展类具有预定义的属性和方法,这些属性和方法将被继承,并且可以重载和设置。这是基类:

class Ext:
    # Info about the extension
    Name    =  Unnamed 
    Author  =  Nobody 
    Version = 0
    Desc    =  This extension has no description 
    Webpage =   

    # Determines whether the extension will automatically be on when added or not
    OnByDefault = False

    def __init__(self): 
        # Overwrite me! You can use me to load files and set attributes at startup
        raise Exception( AbstractClassError: This class must be overloaded )

    def SetName(self, name):
        name = name.split(   )
        name =   .join(name)
        self.Name = name

    def Load(self, file): 
        # Loads a file
        return Misc.read_obj(file)

    def Save(self, file, obj): 
        # Saves a file
        return Misc.write_obj(file, obj)

    def Activate(self, Komodo):
        # When the extension is turned on, this is called
        pass

    def add_cmd(self, Komodo, name, callback, default=False, link=  ):
        # Add a command to the bot
        if name in Komodo.Ext.commands:
            Komodo.logger(msg = ">> Command  {0}  was already defined, so {1} s version of the command couldn t be added".format(
                name, self.meta.name))
        else:
            Komodo.Ext.commands[name] = callback
            if default:
                Komodo.Ext.default_commands.append(name)
            if len(link) > 0:
                Komodo.Ext.links[name] = link

    def add_event(self, Komodo, type, callback):
        # Add an event to the bot
        if type not in Komodo.Ext.trigs:
            Komodo.logger(msg = 
                ">> Could not add  {0}  to event type  {1}  from extension  {2}  because that type does not exist".format(
                str(callback), type, self.name))
        else:
            Komodo.Ext.trigs[type].append(callback)

扩展通常是这样的:

class Extension(Ext):
    def __init__(self, K):  
        self.file =  Storage/Extensions/AI.txt 
        self.SetName( AI )

        self.Version = 1.1
        self.Author  =  blazer-flamewing 
        self.Desc    =  An extension that lets you talk to an Artificial Intelligence program online called Kato. 
        self.Webpage =  http://botdom.com/wiki/Komodo/Extensions/AI 

        try:    self.AI = self.Load(file)
        except: self.AI = {}

    def Activate(self, K):
        print(self.Version)
        self.add_cmd(K,  ai , self.cmd_AI, False,  http://botdom.com/wiki/Komodo/Extensions/AI )
        self.add_event(K,  msg , self.msg_AI)


    ...more methods down here that aren t part of the base class

每一个像这样写的扩展都有效。。。除了一个,上面提到的那个。只有当设置它的Name属性时,它才会成功,而当读取其他属性时,它们仍然是基类设置的属性。在启动时,我循环浏览每个扩展,以打印dict条目、实际名称、版本、作者以及扩展是否打开,结果如下:

Responses Responses 1.2 blazer-flamewing OFF
Ai AI 0 Nobody ON
Notes Notes 1.2 blazer-flamewing OFF
Misc Misc 1.5 blazer-flamewing OFF
System System 2.2 blazer-flamewing ON
Helloworld HelloWorld 1.3 blazer-flamewing OFF
Goodbyes Goodbyes 0 blazer-flamewing OFF
Spamfilter Spamfilter 1.2 blazer-flamewing OFF
Damn dAmn 2.2 blazer-flamewing ON
Bds BDS 0.2 blazer-flamewing OFF
Fun Fun 1.6 blazer-flamewing OFF
Welcomes Welcomes 1.5 blazer-flamewing OFF
Cursefilter Cursefilter 1.7 blazer-flamewing OFF

类似地,Extension.Activate()在打开时对AI不起作用。我认为这与同样的问题有关(设置不正确)

关于为什么没有设置类的属性,有什么想法吗?我已经在这个问题上坚持了几个小时,扩展的设置方式与其他扩展完全相同

编辑:这是另一个扩展,用于比较。这一个实际上有效,Activate()实际上调用了。除了内容外,其他一切都差不多

from komodo.extension import Ext
import time

class Extension(Ext):        
    def __init__(self, K):
        self.SetName( dAmn )
        self.Version = 2.2
        self.Author  =  blazer-flamewing 
        self.Desc    =  Module for all standard dAmn commands such as join, part, and say. 
        self.Webpage =  http://botdom.com/wiki/Komodo/Extensions/dAmn 
        self.OnByDefault = True

    def Activate(self, K):
        self.add_cmd(K,  action ,       self.cmd_action,       False, "http://botdom.com/wiki/Komodo/Extensions/dAmn#Me_or_Action")
        self.add_cmd(K,  ban ,          self.cmd_ban,          False, "http://botdom.com/wiki/Komodo/Extensions/dAmn#Ban_and_Unban")
        self.add_cmd(K,  chat ,         self.cmd_chat,         True,  "http://botdom.com/wiki/Komodo/Extensions/dAmn#Chat")
        self.add_cmd(K,  demote ,       self.cmd_demote,       False, "http://botdom.com/wiki/Komodo/Extensions/dAmn#Demote_and_Promote")
        self.add_cmd(K,  join ,         self.cmd_join,         False, "http://botdom.com/wiki/Komodo/Extensions/dAmn#Join_and_Part")
        ...etc
最佳回答

我解决了自己的问题。原来我有一个覆盖人工智能的扩展,所以它不是人工智能扩展本身。非常感谢你们的帮助。你们每人一个

问题回答

你在课堂上忘记了自己扩展:

try:    self.AI = self.Load(self.file)

另外,也许你的打印测试不准确。你试过单元测试吗?

是否有可能SetName调用下面的块实际上缩进不同(例如,用制表符而不是空格),并且以下行实际上不是__init__的一部分?

我不认为这是你的问题,因为你可以从其他类中得到你想要的东西——但我希望你能看到你没有在继承的类上设置任何“类”属性——你只为它们设置了实例属性。(因此,如果您尝试获取Extension.Version,它将从基类“Ext”中选择属性——只有当您有一个Extension Object时,它的Version属性才会被实例属性“Version”覆盖。

但这并不能解释为什么“激活”不起作用。





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签