qiaoliang0302

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

类当做装饰器

class Test(object):
    def __init__(self,func):
        print("----初始化----")
        print("func name is %s"%func.__name__)
        self.__func = func
    def __call__(self):                 #对象直接被调用
        print("---装饰器中的功能---")
        self.__func()

def test():
    print("----test----")
test()

print("------------")

@Test      # test = Test(test)
def test():
    print("----test----")

test()

 

元类

类也是对象

class Person(object):
    num = 0
    print("----person---test---")
    def __init__(self):
        self.name = "abc"

 

动态的创建类

def choose_class(name):
    if name == 'foo':
        class Foo(object):
            pass
        return Foo
    else:
        class Bar(object):
            pass
        return Bar

MyClass = choose_class('foo')
print(MyClass)      #函数返回的是类,不是类的实例
print(MyClass())    #你可以通过这个类创建类实例,也就是对象

 

使用type创建类

Person2 = type("Person2",(),{"num":0})   #(类名,继承谁,有什么属性)
p1 = Person()
p1.nums
def printNum(self):
    print("---num---%d---"%self.num)
Test3= type("Test3",(),{"printNum":printNum})
t1 = Test3()
t1.num = 100
t1.printNum()
class printNum2:
    def printNum(self):
        print("---num-%d---"%self.num)
t2 = printNum2()
t2.num = 100
t2.printNum()
class Animal:
    def eat(self):
        print("-----eat-----")
class Dog(Animal):
    pass
wangcai = Dog()
wangcai.eat()

Cat = type("Cat",(Animal,),{})   #继承
xiaohuamao = Cat()
xiaohuamao.eat()
class Animal:
    def eat(self):
        print("-----eat-----")
class Dog(Animal):
    pass
wangcai = Dog()
wangcai.eat()

Cat = type("Cat",(Animal,),{})
xiaohuamao = Cat()
xiaohuamao.eat()

print(Animal.__class__)
print(Dog.__class__)
print(type.__class__)
print(wangcai.__class__)
print(xiaohuamao.__class__)

__metaclass__属性

def upper_attr(future_class_name,future_class_parents,future_class_attr):
    #遍历属性字典,把不是__开头的属性名字变为大写
    newAttr = {}
    for name,value in future_class_attr.items():
        if not name.startswith("__"):
            newAttr[name.upper()] = value
    return type(future_class_name,future_class_parents,newAttr)

class Foo(object,metaclass = upper_attr):
    #__metaclass__ = upper_attr     #在python2 中用
    bar = 'bip'

print(hasattr(Foo,'bar'))
print(hasattr(Foo,'BAR'))

t = Foo()
print(t.BAR)
#print(t.bar)

 

垃圾回收(一)

1、小整数对象池   [-5,257)

这些整数对象提前建立好了,不会被垃圾回收。在一个python程序中,所有的位于这个范围内的整数使用的都是同一个对象。

单个字母也是这样。

2、大整数对象池

每一个大整数,均创建一个新的对象。

3、intern机制

a1 = "HelloWorld"

a2 = "HelloWorld"

a3 = "HelloWorld"

a4 = "HelloWorld"

a5 = "HelloWorld"

a6 = "HelloWorld"

a7 = "HelloWorld"

a8 = "HelloWorld"

在内存中一份。

字符串中出现空格、特殊字符等,各用个的。如"hello world"

垃圾回收(二)

1、Garbage collection (GC垃圾回收)

a

b= a

del a

引用计数

以引用计数为主,以为隔代回收为辅

 

ruby  标记清除

python 隔代回收、循环引用

 

import gc
#gc.get_threshold() #获取gc模块中自动执行垃圾回收的频率
#gc.set_threshold() #设置自动执行垃圾回收的频率
#gc.get_count()   # 获取当前自动执行垃圾回收的计数器,返回一个长度为3的列表
#sys.getrefcount(a)  #查看一个对象的引用计数

class ClassA():
    def __init__(self):
        print('object born,id:%s'%str(hex(id(self))))
def f2():
    while True:
        c1 = ClassA()
        c2 = ClassA()
        c1.t = c2
        c2.t = c1
        del c1
        del c2
gc.collect()    #手动清理垃圾回收 #gc.disable()
#关闭gc垃圾回收 f2()

 

gc.garbage     保存了已经清理对象的信息

 

 

内建属性

__init__

__new__
__class__

__str__

__repr__

__del__

__dict__

__doc__

__getattribute__

__bases__

 

class Itcast(object):
    def __init__(self,subject1):
        self.subject1 = subject1
        self.subject2  ="cpp"

    def __getattribute__(self,obj):          #属性拦截器
        if obj == 'subject1':
            print('log subject1')
            return 'redirect python'
        else:
            return object.__getattribute__(self,obj)
    def show(self):
        print('this is Itcast')
s = Itcast("python")
print(s.subject1)
print(s.subject2)

 

print(map(lambda x:x*x,[1,2,3]))
print(map(lambda x,y:x+y,[1,2,3],[4,5,6]))


[1, 4, 9]
[5, 7, 9]

 

def f1(x,y):
    return(x,y)

l1 = [0,1,2,3,4,5,6]
l2 = ['sum','M','T','W','T','F','S']
l3 = map(f1,l1,l2)
print(l3)

[(0, 'sum'), (1, 'M'), (2, 'T'), (3, 'W'), (4, 'T'), (5, 'F'), (6, 'S')]

 

print(filter(lambda x:x%2,[1,2,3,4]))

[1, 3]

 

print(filter(None,"she"))

she

 

print(reduce(lambda x,y:x+y,[1,2,3,4]))

10

 

print(reduce(lambda x,y:x+y,[1,2,3,4],5))
15

print(reduce(lambda x,y:x+y,['aa','bb','cc'],'dd'))
ddaabbcc

 

a = [12,14,31,26,38,19,72,36,41,93,85,76,22,66,74]
a.sort()
print(a)
a.sort(reverse = True)  
print(a)


[12, 14, 19, 22, 26, 31, 36, 38, 41, 66, 72, 74, 76, 85, 93]
[93, 85, 76, 74, 72, 66, 41, 38, 36, 31, 26, 22, 19, 14, 12]

 

print(sorted(['dd','aa','bb','cc']))
print(sorted(['dd','aa','bb','cc'],reverse = 1))

['aa', 'bb', 'cc', 'dd']
['dd', 'cc', 'bb', 'aa']

 

 

集合

l = [1,2,3,4,5,6,7,4,5,6,7,8,9,0,1,2,3,3,4,3]
s = set(l)    #去重
l = list(s)
print(l)

 

a = "abcdef"
b = set(a)
print(b)

A = "bdf"
B = set(A)
print(A)
print(b&B)
print(b|B)
print(b-B)
print(b^B)    #对称差集,(在b或B中,但不会同时出现在两者中)

 

 

import functools
def showarg(*args,**kw):
    print(args)
    print(kw)
p1 = functools.partial(showarg,1,2,3)     # 偏函数
p1()
print("-----------")
p1(4,5,6)
print("-----------")
p1(a = 'python',b = 'itcast')
print("-----------")

p2 = functools.partial(showarg,a = 3,b = 'linux')
p2()
print("-----------")
p2(1,2)
print("-----------")
p2(a = 'python',b = 'itcast')


(1, 2, 3)
{}
-----------
(1, 2, 3, 4, 5, 6)
{}
-----------
(1, 2, 3)
{'b': 'itcast', 'a': 'python'}
-----------
()
{'b': 'linux', 'a': 3}
-----------
(1, 2)
{'b': 'linux', 'a': 3}
-----------
()
{'b': 'itcast', 'a': 'python'}

 

 

import functools
def note(func):
    "note function"
    @functools.wraps(func)      #决定test.__doc__ 显示谁
    def wrapper():
        "wrapper function"
        print('note something')
        return func()
    return wrapper

@note
def test():
    "test function"
    print('I am test')

test()
print(test.__doc__)

 

 

模块

 

posted on 2019-08-11 16:57  qiaoliang0302  阅读(152)  评论(0编辑  收藏  举报