1

[更新]:完整代码

我总是对 pyhton 的静态方法感到困惑,但根据这个(最后一个答案),它应该可以工作!

收到错误:

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

4 回答 4

5

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

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

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

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
于 2013-09-04T19:27:58.390 回答
2

您必须在类范围(静态属性)或实例范围(in __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

查看变量名之前的selfin 。__init__

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

于 2013-09-04T19:36:24.117 回答
2

如果您的目的确实是制作connecta ,则在类级别@staticmethod初始化myhostnamemyportmyuser和,例如:mypassword

    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一个实例方法,那么你就差不多了。您只需要删除 decorator@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()
于 2013-09-04T19:44:13.670 回答
0

classmethod并且static method不能访问 __init__()方法中声明的变量。因为classmethodandstaticmethod 绑定到类而不是类的对象,因此它们采用指向类而不是对象实例的类参数。

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

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

于 2020-09-04T12:13:29.540 回答