class MyClass:
val1 = ‘apple‘
def __init__(self):
val2 = ‘banana‘
@staticmethod
def staticmd():
print val1+":"+val2
@classmethod
def classmd1(cls):
print cls.val2
@classmethod
def classmd2(cls):
print cls.val1>>> MyClass.staticmd()
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-325-e7a1dcd0e04d> in <module>()
----> 1 MyClass.staticmd()
<ipython-input-323-d82dece8064f> in staticmd()
5 @staticmethod
6 def staticmd():
----> 7 print val1+":"+val2
8 @classmethod
9 def classmd(cls):
NameError: global name ‘val1‘ is not defined>>> MyClass.classmd1()
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-327-c83635b87838> in <module>()
----> 1 MyClass.classmd1()
<ipython-input-326-48fb9fb0f284> in classmd1(cls)
8 @classmethod
9 def classmd1(cls):
---> 10 print cls.val2
11 @classmethod
12 def classmd2(cls):
AttributeError: class MyClass has no attribute ‘val2‘
>>> MyClass.classmd2()
applePython的静态方法和类方法,布布扣,bubuko.com
原文:http://blog.csdn.net/magicharvey/article/details/20217357