class MyTest:
myname = 'peter'
# add a instance attribute
def __init__(self, name):
self.name = name
# class access class attribute
def sayhello(self):
print "say hello to %s" % MyTest.myname
# instance can access class attribute
def sayhello_1(self):
print "say hello to %s" % self.myname
# It's a snap! instance can access instance attribute
def sayhello_2(self):
print "say hello to %s" % self.name
# class can not access instance attribute!!!
def sayhello_3(self):
#print "say hello to %s" % MyTest.name
pass
if __name__ == '__main__':
test = MyTest("abc")
test.sayhello()
test.sayhello_1()
test.sayhello_2()
test.sayhello_3()
# class's definition can be changed dynamically
MyTest.yourname = "Allen"
print MyTest.myname
print MyTest.yourname
---------------------------------------------------------------------------------------------------------------------
class Foo:
def func(self):
print "object method"
@classmethod
def cfunc(cls):
print "class method"
@staticmethod
def sfunc(a, b):
print "static method:", a, " + ", b, "=", a + b
if __name__ == '__main__':
foo = Foo()
# instance method can be called by object and class name
foo.func()
Foo.func(foo)
# both instance and class can call class method
foo.cfunc()
Foo.cfunc()
# both instance and class can call static method
Foo.sfunc(10, 20)
foo.sfunc(50, 100)
----------------------------------------------------------------------------------------------------------------------
注