这里主要演示了python的类方法,实例方法,静态方法,类方法可以以 类名.类方法名 的方式调用,也可以以实例对象.类方法名调用,且类方法在定义时需要@classmethod;实例方法必须以实例对象.实例方法名调用;静态方法以类名或者实例名都可以,静态方法需要@statucmethod
class person:
num = 0
def __init__(self, name, age):
self.name = name
self.age = age
"""self.attr_name = attr_value, 所以如果此方法做了限制,可能在__init__方法中的属性赋值也会出现问题"""
def __setattr__(self, attr_name, attr_value):
self.__dict__[attr_name] = attr_value
"""del self.attr_name,这里取决于__getattribute__方法的正确设定"""
def __delattr__(self, attr_name):
del self.__dict__[attr_name]
"""无条件的在获取属性值时使用"""
def __getattribute__(self, attr_name):
"""can not use return self.__dict__[attr_name],这样会导致递归发生,因为获取__dict__时也需要调用__getattribute__(),此方法是绝对的"""
return object.__getattribute__(self, attr_name)
"""未查找到属性值时调用"""
def __getattr__(self, attr_name):
return "Not Defined!"
"""object instance pointer"""
def instance_description(self):
print "I can be called by class instance"
"""cls class pointer"""
@classmethod
def calss_description(cls):
"""print the name of the Class"""
print "I can be called by class: %s" %cls.__name__
"""be called by all"""
@staticmethod
def toolmethod():
print "I am a toolMethod"
def regularMethod():
print "I am a regualr method"
p1 = person("name1", 24)
p1.calss_description()
p1.instance_description()
p1.toolmethod()
person.calss_description()
"""person.instance_description()"""
"""person.instance_description(person("name2", 25))"""
person.toolmethod()
p1.addr = "wuhu"
print p1.wife
print p1.__dict__
del p1.addr
print p1.__dict__
print person.__dict__