静态方法中的python类变量

时间:2013-09-04 19:27:20

标签: python oop static-methods static-variables

[更新]:完整代码

我总是对pyhton的静态方法感到困惑 但根据this(最后的答案),它应该有用!

收到错误:

  

AttributeError:类MyConnection没有属性'myuser'

class MyConnection:
    def __init__(self, hostname, port, user, password):
        myhostname = hostname
        myport = port
        myuser = user
        mypassword = password
        isisessid = None

    @staticmethod
    def connect():
        my_session = MyConnection()

        headers = {'content-type': 'application/json'}
        headers['Authorization'] = 'Basic ' + string.strip(
            base64.encodestring(MyConnection.myuser + ':' + MyConnection.mypassword))

        body = json.dumps({'username': MyConnection.myuser, 'password': MyConnection.mypassword,
            'services': ['platform', 'namespace']})

        uri = '/session/1/session'

        connection = httplib.HTTPSConnection(MyConnection.myhostname, MyConnection.myport)
        connection.connect()

        try:
            connection.request('POST', uri, body, headers)
            response = connection.getresponse()
            my_session.isisessid = MyConnection.extract_session_id(
                response.getheaders())
        except Exception, e:
            print e
            connection.close()
        except httplib.BadStatusLine, e:
            print e
            connection.close()

        return my_session

4 个答案:

答案 0 :(得分:2)

如果属性是静态的,不要在初始化方法中初始化它们,在类级别声明它们之外,而不是在方法级别。

但是为什么要在初始化程序中初始化类属性?您创建的每个实例都将覆盖其值!

我相信您会混淆实例属性和属性的用途。为什么不尝试仅使用实例属性?考虑到所有事情,拥有静态数据是一个好主意。例如:

class MyConnection:
    def __init__(self, hostname, port, user, password):
        self.myhostname = hostname
        self.myport = port
        self.myuser = user
        self.mypassword = password
    @staticmethod
    def connect():
        my_session = MyConnection()
        print my_session.myuser # just an example

答案 1 :(得分:1)

您必须在类范围(静态属性)或实例范围(__init__)中定义属性。

所以在课堂范围内看起来像:

class Cls(object):
    class_scope_attribute = 1

    @staticmethod
    def method1():
        print Cls.class_scope_attribute

    @classmethod
    def metdho2(cls):
        print cls.class_scope_attribute

    def method3(self):
        print Cls.class_scope_attribute
        print self.__class__.class_scope_attribute

在实例范围内:

class Cls2(object):
    def __init__(self):
        self.instance_scope_attribute

    @staticmethod
    def method1():
        # cannot access the instance_scope_attribute
        pass

    @classmethod
    def method2(cls):
        # cannot access the instance_scope_attribute
        pass

    def method3(self):
        print self.instance_scope_attribute

在变量名之前查看self中的__init__

因此,您必须添加self.或将变量移动到类范围,但要注意所有实例共享类范围属性。

答案 2 :(得分:0)

如果您的目的确实是connect @staticmethod,那么请初始化myhostnamemyportmyusermypassword班级,如:

    class MyConnection:
        myhostname= hostnameValue
        myport= portValue
        myuser= userValue
        mypassword= passwordValue

        @staticmethod
        def connect():
            my_session = MyConnection()

            headers = {'content-type': 'application/json'}
            headers['Authorization'] = 'Basic ' + string.strip( base64.encodestring( MyConnection.myuser + ':' + MyConnection.mypassword ) )

            body = json.dumps({'username': MyConnection.myuser, 'password': MyConnection.mypassword,'services': ['platform', 'namespace']})

            my_session.connection = httplib.HTTPSConnection(MyConnection.myhostname, MyConnection.myport)
            my_session.connection.connect()

    MyConnection.connect()

或者,您可以将其保留在None中,并在致电connect()之前为其提供值。

如果你想让connect成为一种实例方法,那么你几乎就是那里。您只需要删除装饰器@staticmethod,然后进行一些其他更改:

    class MyConnection:
        def __init__(self, hostname, port, user, password):
            self.myhostname = hostname
            self.myport = port
            self.myuser = user
            self.mypassword = password

        def connect():
            headers = {'content-type': 'application/json'}
            headers['Authorization'] = 'Basic ' + string.strip( base64.encodestring(self.myuser + ':' + self.mypassword) )

            body = json.dumps({'username': self.myuser, 'password': self.mypassword, 'services': ['platform', 'namespace']})

            connection = httplib.HTTPSConnection(self.myhostname, self.myport)
            connection.connect()

    my_session= MyConnection(hostnameValue,portValue,userValue,passwordValue)
    my_session.connect()

答案 3 :(得分:0)

classmethodstatic method无法访问在__init__()方法中声明的变量。 由于classmethodstaticmethod绑定到类而不是类的对象,因此它们采用指向类而不是对象实例的类参数。

__init__()创建对象实例,因此__init__()classmethod不能访问staticmethod中声明的变量,除非将它们声明为类变量。

他们可以修改适用于该类所有实例的类状态。例如,他们可以修改将适用于所有实例的类变量。