zoukankan      html  css  js  c++  java
  • python 类中的特殊成员

    在Python的类中存在一些特殊的方法,这些方法都是 __方法__ 格式,这种方法在内部均有特殊的含义,接下来我们来讲一些常见的特殊成员:

    1. __init__,初始化方法
    class Foo(object):
        def __init__(self, name):
            self.name = name
    
    
    obj = Foo("dhc") # 初始化对象
    
    
    1. __new__,构造方法
    class Foo(object):
        def __init__(self, name):
            print("第二步:初始化对象,在空对象中创建数据")
            self.name = name
    
        def __new__(cls, *args, **kwargs):
            print("第一步:先创建空对象并返回")
            return object.__new__(cls)
    
    
    obj = Foo("dhc")
    
    1. call 执行方法
    class Func(object):
        def __init__(self,name):
            self.name = name
        def __call__(self, *args, **kwargs):
            print(args,self.name)
    
    obj = Func('dhc')
    obj('test1','test2') # 结果: ('test1', 'test2') dhc
    
    1. str 方法
    # 让对象支持str(对象)
    class Str_Test(object):
        def __str__(self):
            return "123"  # 返回的值首先满足字符串条件
    obj = Str_Test()
    v1 = str(obj)
    print(v1)  # 123  
    
    
    1. dict
    class Dict_test():
        country = 'ch'
        def __init__(self,name,age):
            self.name = name
            self.age = age
        def test(self):
            print(123)
    obj = Dict_test
    print(obj.__dict__)  # 显示类里面的所有变量和方法
    
    #  {'__module__': '__main__', 'country': 'ch', '__init__': <function Dict_test.__init__ at 0x000001A766136D08>, 'test': <function Dict_test.test at 0x000001A766139400>, '__dict__': <attribute '__dict__' of 'Dict_test' objects>, '__weakref__': <attribute '__weakref__' of 'Dict_test' objects>, '__doc__': None}
    
    
    1. __getitem____setitem____delitem__
    #让对象可以和列表,字典等一样进行操作
    class Item_test():
        def __getitem__(self, item):
            pass
        def __setitem__(self, key, value):
            pass
        def __delitem__(self, key):
            pass
    obj = Item_test()
    x = obj['v1']
    obj['v1'] = 123
    del obj['v2']
    
    
    1. __enter____exit__
    # 配合with xxx as xx 来实现一进一出
    class With_Test:
        def __enter__(self):
            print('enter')
            return '返回值'
        def __exit__(self, exc_type, exc_val, exc_tb):
            print('exit')
    obj = With_Test()
    
    with obj as a:
        print(a)
    # enter
    # 返回值  # as a 中的a 指的就是enter的返回值
    # exit
    # 一般配合对数据库的连接等,每次操作进入,操作完关闭连接等
    
    1. add 方法
    # 让类拥有相加的功能
    class Foo(object):
        def __init__(self, name):
            self.name = name
    
        def __add__(self, other):
            return "{}-{}".format(self.name, other.name)
    
    
    v1 = Foo("a")
    v2 = Foo("b")
    
    # 对象+值,内部会去执行 对象.__add__方法,并将后面的值当作参数传递过去
    v3 = v1 + v2
    print(v3)
    
    1. iter 迭代器
      迭代器定义: 当类中定义了__iter__,和__next__ 两个方法
      其中 iter 放回对象本身,self
      next 返回下一个数据,如果数据没用了,则抛出一个StopIteration的异常。
      这个是我们日常中使用最多的特殊方法。
    # 创建迭代器
    class Iter_test:
        def __init__(self,count):
            self.count = count
            self.num = 0
        def __iter__(self):
            return  self
        def __next__(self):
            self.num += 1
            if self.num == self.count:
                raise StopIteration
            return self.num
    obj = Iter_test(10)
    # print(obj.__next__())
    # print(obj.__next__())
    # print(obj.__next__()) # 当连续输出第10次的时候,报错异常
    for i in obj:   # 很range 的输出结果一样,首先执行__iter__方法,获取一个迭代器对象,然后不断的执行next方法,知道有StopIteration异常为止
        print(i)
    
    
  • 相关阅读:
    Football Foundation (FOFO) TOJ 2556
    JAVA- String类练习
    JAVA- 清除数组重复元素
    Mysql远程登陆错误:ERROR 2003
    Linux学习之路(五)压缩命令
    Linux学习之路(四)帮助命令
    如何识别真Microsoft服务与非Microsoft服务来定位病毒自己的服务
    如何用命令行删除EasyBCD开机选择项?
    JAVA- 成员变量与局部变量的区别
    JAVA- 内部类
  • 原文地址:https://www.cnblogs.com/dinghc/p/15543930.html
Copyright © 2011-2022 走看看