代码
# file's name : MethodAndVariable.py

class Person:
    
"""This is a test for class's method, static method, instance method.
And class's variable, instance's variable
"""
    class_variable 
= 1

    
def __init__(self, name):
        self.name 
= name
        
print "__init__ method called..."

    
def __del__(self):
        
print "__del__ method called..."

    
def sayHi(self, name):
        
print self, "Hello %s, my name is %s" % (name, self.name)

    @classmethod
    
def class_method(cls, x):
        
print cls, ", x =", x

    @staticmethod
    
def static_method(x):
        
print "x =", x

    
def global_method(x):
        
print "x =", x


p1 
= Person("zhang")

p1.sayHi(
"koma")
p1.class_method(
9)
p1.static_method(
7)
Person.class_method(
12)
Person.static_method(
17)

print p1.class_variable
print Person.class_variable

p1.class_variable 
= 8
print p1.class_variable
print Person.class_variable

Person.class_variable 
= 5
print p1.class_variable
print Person.class_variable

del p1.class_variable
print p1.class_variable
print Person.class_variable

del p1

运行结果:
__init__ method called...
<__main__.Person instance at 0x00DBEDF0> Hello koma, my name is zhang
__main__.Person , x = 9
x = 7
__main__.Person , x = 12
x = 17
1
1
8
1
8
5
5
5
__del__ method called...

 

注意:obj.class_variable 只能读取类变量的值,而不能修改,修改其实是创建了一个实例变量,该变量名与类变量名一样。

相关文章:

  • 2021-12-23
  • 2022-12-23
  • 2022-02-13
  • 2022-12-23
  • 2021-11-25
  • 2021-07-09
猜你喜欢
  • 2018-12-02
  • 2022-03-05
  • 2021-10-22
  • 2021-09-20
  • 2021-06-24
  • 2022-02-03
相关资源
相似解决方案