1

私はここで完全な python n00b であり、いくつかのビットを組み合わせてプロジェクトを機能させようとしていますが、私が考える構文のいくつかに苦労しています。

ここに私がこれまでに持っている私のスクリプトがあります:

#!/usr/bin/env python

from plugin import *
from siriObjects.systemObjects import ResultCallback
import uuid
import json
import random
import types
import urllib
import urllib2
import random
import re
import select
import socket
import struct
import sys
import thread
import time

class tivoRemote(Plugin):

        tivo_address = '192.168.0.9'
        tivo_name = ''
        tivo_swversions = {}
        have_zc = True
        captions_on = False
        sock = None
        outer = None


        def connect():
            """ Connect to the TiVo within five seconds or report error. """
            global sock
            try:
                sock = socket.socket()
                sock.settimeout(5)
                sock.connect((tivo_address, 31339))
                sock.settimeout(None)
            except Exception, msg:
                msg = 'Could not connect to %s:\n%s' % (tivo_name, msg)
                print(msg)

        def send(message):
            """ The core output function, called from irsend(). Re-connect if
                necessary (including restarting the status_update thread), send
                message, sleep, and check for errors.
                """

            if not sock:
                self.connect()
                thread.start_new_thread(status_update, ())
            try:
                sock.sendall(message)
                time.sleep(0.1)
            except Exception, msg:
                error_window(str(msg))


        def irsend(*codes):
            """ Expand a command sequence for send(). """
            for each in codes:
                self.send('IRCODE %s\r' % each)


        @register("en-US", ".*Change.*Channel.*")
        def channelChanger(self, speech, language, matchedRegex):
                if language == 'en-US':
                        answer = self.ask(u"Which channel would you like?")
                        self.say(u"Ok, one moment..".format(answer))
                        self.connect()
                        self.irsend(answer)
                self.complete_request()

私が得ているエラーは次のとおりです。

Traceback (most recent call last):
  File "/home/pi/SiriServerCore/plugin.py", line 150, in run
    self.__method(self, self.__speech, self.__lang,        self.__method.__dict__[__criteria_key__][self.__lang].match(self.__speech))
  File "/home/pi/SiriServerCore/plugins/tivoRemote/__init__.py", line 70, in     channelChanger
    self.irsend(format(answer))
  File "/home/pi/SiriServerCore/plugins/tivoRemote/__init__.py", line 61, in irsend
    self.send('IRCODE %s\r' % each)
NameError: global name 'self' is not defined

「自己」を削除すると。同じエラーが発生しますが、「送信」は定義されていません。

事前に助けてくれてありがとう:)ライアン

4

4 に答える 4

3

動作する可能性が高い:

class tivoRemote(Plugin):

    def __init__(self):
        self.tivo_address = '192.168.0.9'
        self.tivo_name = ''
        self.tivo_swversions = {}
        self.have_zc = True
        self.captions_on = False
        self.sock = None
        self.outer = None


    def connect(self):
        """ Connect to the TiVo within five seconds or report error. """
        try:
            sock = socket.socket()
            sock.settimeout(5)
            sock.connect((tivo_address, 31339))
            sock.settimeout(None)
        except Exception, msg:
            msg = 'Could not connect to %s:\n%s' % (tivo_name, msg)
            print(msg)
        self.sock = sock

    def send(self, message):
        """ The core output function, called from irsend(). Re-connect if
            necessary (including restarting the status_update thread), send
            message, sleep, and check for errors.
        """

        if not self.sock:
            self.connect()
            thread.start_new_thread(status_update, ()) # status_update must be some global at this point
        try:
            self.sock.sendall(message)
            time.sleep(0.1)
        except Exception, msg:
            error_window(str(msg))


    def irsend(self, *codes):
        """ Expand a command sequence for send(). """
        for each in codes:
            self.send('IRCODE %s\r' % each)


    @register("en-US", ".*Change.*Channel.*")
    def channelChanger(self, speech, language, matchedRegex):
            if language == 'en-US':
                    answer = self.ask(u"Which channel would you like?")
                    self.say(u"Ok, one moment..".format(answer))
                    self.connect()
                    self.irsend(answer)
            self.complete_request()

selfメソッドを定義するときに使用する必要があり、現在のインスタンスにアクセスするために使用する必要があります。

于 2012-07-18T15:46:00.823 に答える
1

作成しているメンバー変数は、インスタンスではなくクラスに属します (クラス内で変数を定義する方法)。のようなメソッドsend()がインスタンスから呼び出される場合、それらの関数の最初の引数は でなければなりませんself。コード全体を次のように変更する必要があります。

class tivoRemote(..):
    def __init__(self):
        self.tivo_address = '192.168.0.9'
        self.tivo_name = '' #and so on for other members
        ....

    def send(self, msg):
        self.connect()
        self.sendall(..)

    def connect(self, ...):
        #self.sock
        self.sock = socket.socket()
        ....

    #and similar for all other method that you think is a part of "instance" add the 
    #first parameter as self
于 2012-07-18T15:48:21.227 に答える
1

すべてのインスタンス メソッド ( でアクセスするself.) をself最初の引数として定義する必要があります。慣れるでしょう:

class tivoRemote(Plugin):

    tivo_address = '192.168.0.9'
    tivo_name = ''
    tivo_swversions = {}
    have_zc = True
    captions_on = False
    sock = None
    outer = None


    def connect(self):
        """ Connect to the TiVo within five seconds or report error. """
        global sock
        try:
            sock = socket.socket()
            sock.settimeout(5)
            sock.connect((tivo_address, 31339))
            sock.settimeout(None)
        except Exception, msg:
            msg = 'Could not connect to %s:\n%s' % (tivo_name, msg)
            print(msg)

    def send(self, message):
        """ The core output function, called from irsend(). Re-connect if
            necessary (including restarting the status_update thread), send
            message, sleep, and check for errors.
            """

        if not sock:
            self.connect()
            thread.start_new_thread(status_update, ())
        try:
            sock.sendall(message)
            time.sleep(0.1)
        except Exception, msg:
            error_window(str(msg))


    def irsend(self, *codes):
        """ Expand a command sequence for send(). """
        for each in codes:
            self.send('IRCODE %s\r' % each)


    @register("en-US", ".*Change.*Channel.*")
    def channelChanger(speech, language, matchedRegex):
            if language == 'en-US':
                    answer = self.ask(u"Which channel would you like?")
                    self.say(u"Ok, one moment..".format(answer))
                    self.connect()
                    self.irsend(answer)
            self.complete_request()

また、これらのプロパティを (静的プロパティのように) クラスではなくインスタンスに属させたい場合は、コンストラクト (コンストラクト__init__に最も近いもの) でそれらを定義する必要があります。

class tivoRemote(Plugin):
    def __init__(self):
        self.tivo_address = '192.168.0.9'
        self.tivo_name = ''
        self.tivo_swversions = {}
        self.have_zc = True
        self.captions_on = False
        self.sock = None
        self.outer = None
于 2012-07-18T15:42:11.887 に答える
0

説明:

class MyThing(object):
    """I am a class definition

    Everything here is part of the class definition.

    Methods here are classmethods, they are considered "unbound"

    When you create an instance of this class like so:
        my_instance_of_class_MyThing = MyThing()

    the "my_instance_of_class_MyThing" now points to an object.

    that object is an instance object.

    that object is an instance object of MyThing

    the "my_instance_of_class_MyThing" now points to an instance object.

    the methods contained in the instance object are NOW "bound" to the instance

    bound methods are bound to an instance object

    bound methods are sent a reference to the thing they are bound too by
       python itself when they are called.
    """

    i_am_a_class_attribute = "I am a class attribute"

    def __init__(self):

        """ I am a method. I start my life as a class method unbound to
        any instance. Because I am unbound, when you call me I will
        complain to you in the form of an unbound exception call, thus
        likely crashing your application.

        When you create an instance the class I was defined in, 
        I will copy a bound copy of myself into the newly created instance.
        When you call the bound copy of myself, Python will politely send
        a reference of the instance object to the bound method as its 
        very first argument. Many people name that varible "self". Some use
        "me". Others programmers break with convention and use a 
        single character, but this is rare. 
        """


        i_am_a_init_local_reference_to = 
            "this string and only visible with in __init__()"


        # self is a variable name python sends to mything_instance.__init__() as the first argument
        # self points to the same thing mything_instance points to, 
        #     an INSTANCE of the class MyThing

        self.i_am_an_instance_reference_to = 
            '''this string and is visible to everthing that can access what "self" points too.'''


    def proof(self):
        try:
            print i_am_a_init_local_reference_to
        except AttributeError, error_message:
            print error_message
        else:
            print "This won't happen !!"
            print "It successfully printed i_am_a_init_local_reference_to"

        try:
            print self.i_am_an_instance_reference_to
        except AttributeError, error_message:
            print error_message
        else:
            print """See proof() can access self.i_am_an_instance_reference_to"""

これが、解決策が与えられた理由を知らなかった人に役立つことを願っています。

于 2012-07-18T18:32:30.693 に答える