装饰的功能@staticmethod
和装饰的功能有什么区别@classmethod
?
有关于如何从静态方法访问静态变量(如大量的回答这一个,和那一个,而关于这个主题的伟大的信息在这里),但我在与其他方向的麻烦:如何使用静态方法初始化静态变量.例如:
import os, platform
class A(object):
@staticmethod
def getRoot():
return 'C:\\' if platform.system() == 'Windows' else '/'
pth = os.path.join(A.getRoot(), 'some', 'path')
Run Code Online (Sandbox Code Playgroud)
最后一行给出了一个例外:NameError: name 'A' is not defined
.如果我使用@classmethod
而不是,则会发生同样的错误@staticmethod
.
是否可以从类变量访问静态方法?
[更新]:完整代码
我总是对 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() …
Run Code Online (Sandbox Code Playgroud)