首页 > 编程语言 > 详细

Python内置方法与面向对象知识点进阶系列

时间:2020-05-23 10:30:06      阅读:63      评论:0      收藏:0      [点我收藏+]

Python中类的魔法方法与内置方法汇总

之前总结的一些双下划线方法

常见的类的内置方法 ***

使用__getitem__与__len__实现一个可迭代/可计算长度的对象

class Company(object):
    #魔法函数
    def __init__(self, employee_list):
        self.employee = employee_list

    def __getitem__(self, item):
        return self.employee[item]
    # 不写它只有__getitem__的话还是能使用len求出长度的
    def __len__(self):
        return len(self.employee)


company = Company(["tom", "whw", "jane"])
#
# for i in company.employee:
#     print(i)

company1 = company[:2]
# 调用__len__方法
print(len(company)) # 3
# 调用__getitem__方法
for em in company1:
    print(em)
"""
tom
whw
"""

super方法

# 使用super函数
# 当前的类和对象可以作为super函数的参数使用,调用返回的对象的任何方法都是
# super函数会自动寻找他所需要的特性,直到返回一个AttributeError异常
class Bird:
    def __init__(self):
        self.hungry=True
    def eat(self):
        if self.hungry:
            print("eat")
            self.hungry=False
        else:
            print("no")

class SongBird(Bird):
    def __init__(self):
        super(SongBird,self).__init__()
        self.sound="lalala"

    def sing(self):
        print(self.sound)

sb=SongBird()
sb.sing() # lalala
sb.eat() # eat
sb.eat() # no

使用__getitem__与super实现一个带有访问计数的list子类

# 子类化列表,字典和字符串
# 带有访问计数的列表
class CounterList(list):
    def __init__(self,*args):
        super(CounterList,self).__init__(*args)
        self.counter=0
    
    def __getitem__(self, item):
        self.counter+=1
        return super(CounterList,self).__getitem__(item)
c1=CounterList(range(10))
print(c1) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
c1.reverse()
print(c1) # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
del c1[3:5]
print(c1) # [9, 8, 7, 4, 3, 2, 1, 0]
print(c1.counter) # 0
print(c1[4]+c1[2]) # 10
print(c1.counter) # 2

property函数

# property函数
# 将访问器函数被用作参数
class Rectangle:
    def __init__(self):
        self.width=0
        self.height=0

    def setSize(self,size):
        self.width,self.height=size

    def getSize(self):
        return self.width,self.height
    
    size=property(getSize,setSize)

r=Rectangle()
r.width=10
r.height=5
print(r.size) # (10, 5)
r.size=150,100
print(r.width) # 150

静态成员方法与类成员方法

# 静态成员方法和类成员方法
class MyClass:
    def smeth():
        print("This is a static method")
    smeth=staticmethod(smeth)

    def cmeth(cls):
        print("This is a class methon of‘",cls)
        cmeth=classmethod(cls.cmeth)

#装饰器
class MyClass1:
    @staticmethod
    def smeth():
        print("This is a static method")

    @classmethod
    def cmeth(cls):
        print("This is a class method",cls)

cla=MyClass1()
cla.smeth() # This is a static method
cla.cmeth() # This is a class method <class ‘__main__.MyClass1‘>

__getattr__与__setattr__

#__getattr__、__setattr__
class Rectangle:
    def __init__(self):
        self.width=0
        self.height=0

    def __setattr__(self, key, value):
        if key==size:
            self.width,self.height=value
        else:
            self.__dict__[key]=value

    def __getattr__(self, item):
        if item==size:
            return self.width,self.height
        else:
            raise AttributeError

d=Rectangle()
d.height=10
d.width=10
print(d.__getattr__(item=size)) # (10, 10)
d.__setattr__(key=size,value=(100,200))
print(d.height) # 200

__iter__与__next__方法简介

一个实现了__iter__方法的对象是可以迭代的,一个实现了__next__方法的对象则是迭代器!

# 迭代时候最好不要用列表,如果有很多值,列表会占用太多的内存
# 使用迭代器更通用,更简单,更优雅。
class Fibs:
    def __init__(self):
        self.a=0
        self.b=1

    def __next__(self):
        self.a,self.b=self.b,self.a+self.b
        return self.a

    def __iter__(self):
        return self

# 一个实现了__iter__方法的对象是可以迭代的,一个实现了__next__方法的对象则是迭代器
fibs=Fibs()

for f in fibs:
    if f>1000:
        print(">>>",f)
        break

#内建函数iter可以从可迭代的对象中获得迭代器
it=iter([1,2,3])
print(next(it))
print(next(it))
print(next(it))
"""
>>> 1597
1
2
3
"""

从迭代器得到序列

# 除了再迭代器和可迭代对象向上进行迭代,还可以把他们转换成序列
class TestIterator:
    value=0

    def __next__(self):
        self.value+=1
        if self.value>10:raise StopIteration
        return self.value

    def __iter__(self):
        return self

t1=TestIterator()
print(list(t1)) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

八皇后问题

# 八皇后问题
# 首先寻找冲突
# 找到一种没有冲突的位置(没有皇后会被其他的皇后吃掉)
def conflict(state,nextX):
    nextY=len(state)
    for i in range(nextY):
        if abs(state[i]-nextX) in (0,nextY-i):
            return True
    return False

# 基本情况
# 周后一个皇后能够根据其他皇后的位置生成他自己能占据的位置
def queens(num,state):
    if len(state)==num-1:
        for pos in range(num):
            if not conflict(state,pos):
                yield pos


# 需要递归的情况
# 递归函数需要假定所有的来自低层的结果都是正确的
# 假定将位置信息作为一个元组返回,需要修改基本情况也返回一个元组
# 这样一来,程序会从前面的皇后得到包含位置的元组信息,并且为后面的皇后提供当前皇后的每种合法位置信息
def queens2(num=8,state=()):
        for pos in range(num):
            if not conflict(state,pos):
                if len(state)==num-1:
                    yield (pos,)
                else:
                    for result in queens2(num,state+(pos,)):
                        yield (pos,)+result

# 打包输出
def prettyprint(solution):
    def line(pos,length=len(solution)):
        return . *(pos)+X +. *(length-pos-1)
    for pos in solution:
        print(line(pos))

import random
prettyprint(random.choice(list(queens2(100))))

Python中类的归一化设计

类的归一化设计abc模块与自定义归一化设计

isinstance与type

聊一聊isinstance与type

类与对象进阶

 

123

123

 

123

123

123

Python内置方法与面向对象知识点进阶系列

原文:https://www.cnblogs.com/paulwhw/p/12940991.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!