python对象与属性相关的特殊方法

这里主要演示了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__


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值