您的位置:首页 > 编程语言 > Python开发

python基础3--面向对象--类变量、实例变量、类方法、静态方法、实例方法

2010-11-14 22:42 876 查看
代码

# 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 只能读取类变量的值,而不能修改,修改其实是创建了一个实例变量,该变量名与类变量名一样。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐