python----面向对象---内置方法

内置方法

1.dir :使用dir获取一个对象或者类的属性和方法

如果引用的是对象,就返回实例属性和方法
如果引用的是类,就返回类属性和方法

class Student(object):
    x=1
    y=2
    def __init__(self):
        self.name = 'Michael'

    def __getattr__(self, item):
        if item == 'grade':
            return 'A'
        if item == 'age':
            return lambda: 25
        raise AttributeError('\'Student\' object has no attribute \'%s\'' % item)

s = Student()
print(s.__dict__)
print(Student.__dict__)
{'name': 'Michael'}
{'__module__': '__main__', 'x': 1, 'y': 2, '__init__': <function Student.__init__ at 0x00000219CEB5E378>, '__getattr__': <function Student.__getattr__ at 0x00000219CFC28488>, '__dict__': <attribute '__dict__' of 'Student' objects>, '__weakref__': <attribute '__weakref__' of 'Student' objects>, '__doc__': None}
2.hasattr getattr setattr delattr

已知

class Student(object):

    def __init__(self,name,score):
        self.__name = name
        self.__score = score
        self.grade = 6

    def set_name(self,name):
        self.__name = name

    def set_score(self,score):
        if score<0:
            return 'score must more than 0'
        elif score>100:
            return 'score must less than 100'
        else:
            self.__score = score

    def get_name(self):
        return self.__name

    def get_score(self):
        if self.__score < 60:
            return 'D'
        elif self.__score < 80:
            return 'C'
        elif self.__score < 90:
            return 'B'
        else:
            return 'A'
  • hasattr 判断一个对象是否有name属性或者name方法。有就返回True,没有就返回False
s = Student('tony',20)
print(hasattr(s,'grade')) #True
print(hasattr(s,'set_name')) #True
  • getattr 获取对象的属性或者方法,如果存在则打印出来。hasattr和getattr配套使用
    需要注意的是,如果返回的是对象的方法,返回出来的是对象的内存地址,如果需要运行这个方法,可以在后面添加一对()
  • setattr 给对象的属性赋值,若属性不存在,先创建后赋值
if hasattr(s,'grade'):
    setattr(s,'grade',6)  
    print(getattr(s,'grade')) # 6
    print(getattr(s,'age',15)) # 15 若对象中没有该属性,则15为默认值
if hasattr(s,'set_name'):
    setname = getattr(s,'set_name')
    setname('Stack')
    getname = getattr(s,'get_name')
    print(getname()) # Stack
  • delattr:删除该对象指定的一个属性
delattr(s,'grade')
print(s.grade)
AttributeError: 'Student' object has no attribute 'grade'
3.触发__setattr__,和__delattr__,和__getattr__的时机

分别是设置属性,删除属性,和获取的属性不存在时触发,并且,只能是实例属性和方法!!!

class Foo:
    x=1
    def __init__(self,y):
        self.y=y

    def __getattr__(self, item):
        print('----> from getattr:你找的属性不存在')


    def __setattr__(self, key, value):
        print('----> from setattr')
        # self.key=value #这就无限递归了,你好好想想
        self.__dict__[key]=value #应该使用它

    def __delattr__(self, item):
        print('----> from delattr')
        # del self.item #无限递归了
        self.__dict__.pop(item)

#__setattr__添加/修改属性会触发它的执行
f1=Foo(10)
print(f1.__dict__) # 因为你重写了__setattr__,凡是赋值操作都会触发它的运行,你啥都没写,就是根本没赋值,除非你直接操作属性字典,否则永远无法赋值
f1.z=3
print(f1.__dict__)

#__delattr__删除属性的时候会触发
f1.__dict__['a']=3#我们可以直接修改属性字典,来完成添加/修改属性的操作
del f1.a
print(f1.__dict__)

#__getattr__只有在使用点调用属性且属性不存在的时候才会触发
f1.x  # x不是实例属性
print('---------',f1.y) # y是实例属性,但它已经存在
f1.xxxxxx

补充,__getattribute,获取属性时,不论属性是否存在,getattribute都会执行

    def __getattribute__(self, item):
        print('不管是否存在,我都会执行')

当__getattribute__与__getattr__同时存在,只会执行__getattrbute__,除非__getattribute__在执行过程中抛出异常AttributeError

4.getitem setitem delitem

这三个方法可以使操作对象变得和操作列表一样

class Boo:
    def __init__(self):
        self.name = 'Jack'
        self.age = 60
        self.grade = 10

    def __getitem__(self, item):
        return 234

    def __setitem__(self, key, value):
        self.__dict__[key] = value
        return 'set_item'

    def __delitem__(self, key):
        print(key)
        # delattr(self, 'grade')
        del self.__dict__[key]
b = Boo()
print(b[1])  # 执行了getitem 234
b['grade'] = 12
print(b.grade) # 执行了setitem grade = 12
del b['grade']  # 执行了delitem 删除grade
print(b.grade)
5.__get,__set,__delete方法(这三个方法是针对于描述符)
  • get 调用属性触发
  • set 设置属性值触发
  • delete 删除属性触发
class Foo:
    def __get__(self, instance, owner):
        print('执行Foo get')
    def __set__(self, instance, value):
        print('执行Foo set')
        print('----',instance,value)
    def __delete__(self, instance):
        print('执行Foo del')

class Skt:
    x = Foo()
    def __init__(self,n):
        self.x = n

s = Skt(10)

s.x
s.x = 12
del s.x
执行Foo set
---- <__main__.Skt object at 0x0000021918994048> 10
执行Foo get
执行Foo set
---- <__main__.Skt object at 0x0000021918994048> 12
执行Foo del

参考:http://www.cnblogs.com/linhaifeng/articles/6204014.html

6.python3中__get__,getattr,__getattribute__的区别

https://www.cnblogs.com/Vito2008/p/5280216.html

7.str 和 repr
class Student(object):
    def __init__(self,name):
        self.name = name

    def __str__(self):  # 返回用户看到的字符串
        return 'Student Name is %s' %(self.name)

    __repr__ = __str__ # 返回程序开发者看到的字符串

print(Student('Michel'))
s = Student('Duck')
print(s)
Student Name is Michel
Student Name is Duck
8.cell 对象后面加括号,触发执行

注:构造方法的执行是由创建对象触发的,即:对象 = 类名() ;而对于 call 方法的执行是由对象后加括号触发的,即:对象() 或者 类()()

class Student(object):
    def __init__(self, name):
        self.name = name

    def __call__(self):
        print('My name is %s.' % self.name)

s = Student('Michel')
print(s())
print(callable(s)) # 被调用的对象就是一个Callable对象,可以被当作函数执行
print(callable('str'))
9.init 和new的区别

https://www.cnblogs.com/suntp/p/6445286.html
https://blog.csdn.net/qq_41020281/article/details/79638370

10.iter next

iter返回一个迭代对象,使类对象可以用于for in循环
next返回循环的下一个值,直到遇到StopIteration错误时退出循环

class Too(object):
    def __init__(self):
        self.no = 1

    def __iter__(self):
        return self

    def __next__(self):
        self.no += 1
        if self.no > 10:
            raise StopIteration('no > 10, stop')
        return self.no

t = Too()
for x in t:
    print(x)
11.__del方法:析构方法

垃圾回收时触发

12.__enter , __exit使类支持上下文管理协议

with Foo(‘a.txt’)as f:
先执行Foo的enter,执行完毕后执行exit

  • with代码块中的异常会触发Exit方法
  • 若exit方法返回True,则该异常会被捕获
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值