[更新]:完整代码
我总是对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
答案 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
,那么请初始化myhostname
,myport
,myuser
和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
成为一种实例方法,那么你几乎就是那里。您只需要删除装饰器@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)
classmethod
和static method
无法访问在__init__()
方法中声明的变量。
由于classmethod
和staticmethod
绑定到类而不是类的对象,因此它们采用指向类而不是对象实例的类参数。
__init__()
创建对象实例,因此__init__()
和classmethod
不能访问staticmethod
中声明的变量,除非将它们声明为类变量。
他们可以修改适用于该类所有实例的类状态。例如,他们可以修改将适用于所有实例的类变量。