python 2023

一切对象都是type类创建出来的  

一切对象的基类都是object

对象的特点:

  1、唯一标识 id()

        2、类型 type()

        3、值

None类型全局只有一个

a=10
print(id(a))
print(type(a))
print(type(int))
print(a)
def fun():
    print(111)
print(id(fun))
print(type(fun))
print(fun)
class Student:
    def __init__(self):
        pass
print(id(Student))
print(type(Student))
print(Student)
####
140718017992000
<class 'int'>
<class 'type'>
10
2662809125344
<class 'function'>
<function fun at 0x0000026BFBCAC1E0>
2662843633544
<class 'type'>
<class '__main__.Student'>
def my_wrapper(funobj):
    def wrapper():
        print('这是一个装饰器')
        funobj()
    return wrapper
@my_wrapper
def fun():
    print('这是一个函数')
#my_wrapper(fun)()
fun()
print(type(fun))
print(type(object)) ##<class 'type'>
a=12
print(type.__bases__) ##__bases__ 看继承关系 object
print(type.__bases__) ## ()
class Student:
    def __init__(self,arr):
        self.arr=arr
    def __getitem__(self, item):##可以让当前类具有序列取值
        print(item)
        return self.arr[item]
stu=Student(['aa','bb','cc'])
for s in stu:
    print(s)

 

class Student:
    def __init__(self,arr):
        self.arr=arr
    def __getitem__(self, item):##可以让当前类具有序列取值
        print(item)
        return self.arr[item]
    def __len__(self):
        return len(self.arr)
    def __str__(self):
        return '这是__str__'
    def __repr__(self):
        return '这是__repr__'
stu=Student(['aa','bb','cc']) ## __init__
for s in stu:  ## __getitem__
    print(s)
print(len(stu)) ## __len__
print(stu)      ## __str__
stu             ## __repr__

 

class Cat:
    def say(self):
        print("i am cat")
class Dog:
    def say(self):
        print("i am dog")
class Duck:
    def say(self):
        print("i am duck")
# animal=Duck
# animal().say()
animals=[Cat,Dog,Duck]
for animal in animals:
    animal().say()

class Person:
    def __init__(self,arr):
        self.arr=arr
    def __getitem__(self, item):
        return self.arr[item]

persons=Person(["张三","李四"])
arr=['王五']
arr_tuple=('lisi',)
arr.extend(persons) ##多个类实现同一方法 __getitem__
arr.extend(arr_tuple)
print(arr)

class Aniaml:
    def run(self):
        print("animal run...")
class Dog(Aniaml):
    def run(self):
        print("Dog run...")
class Cat(Aniaml):
    def run(self):
        print("Cat run...")
class Duck(Aniaml):
    def run(self):
        print("Duck run...")
def animal_run(animal):##多态
    animal.run()
dog=Cat()##多态
#dog.run()
animal_run(dog)

 

from abc import ABC,abstractmethod
class Cache(ABC):
    @abstractmethod
    def get_cache(self):
        pass

    @abstractmethod
    def set_cache(self,value):
        pass
class Redis(Cache):
    def __init__(self):
        self.val=''
    def get_cache(self):
        return self.val
    def set_cache(self,value):
        self.val=value
redis=Redis()
redis.set_cache('aaa')
print(redis.get_cache())
##判断对象为继承关系
print(isinstance(redis,Cache)) ##true
print(isinstance(redis,Redis)) ##true
##判断两个值是否相等
print(type(redis)==Redis) ##true
print(type(redis)==Cache) ##false
##判断内存地址
print(type(redis) is Redis) ##true
print(type(redis) is Cache) ##false

class D:
    #name='D'
    pass
class B(D):
    # name='B'
    pass
class C(D):
    name='C'
class A(B,C):
    pass
a=A()##D C B A菱形继承
print(a.name) ##属性查找  先找自身没有向上(继承顺序B C)找B 然后再找同级C 若都没有再向上D
class F:
    name='F'
class E(F):
    name='E'
class A(B,E):
    pass
a=A()##D F B E A树形继承
print(a.name) ##属性查找  先找自身没有向上找B 若没有再找D 若D没有再返回找同级E 若都没有再向上F

 

class Person:
    addr='guangdong'
    def __init__(self,name):
        self.name=name
    def objMethod(self):
        print(self.addr)
    @staticmethod ##静态方法无法访问类实例属性和方法
    def staticMethod():
        print(Person.addr)
        return Person('bb')
    @classmethod
    def classMethod(cls):
        print(cls.addr)
        return cls('cc')
    # def __str__(self):
    #     print('name:'+self.addr)

per=Person('aa')
per.objMethod()
#per.staticMethod()
per1=Person.staticMethod()
print(per1)
#per.classMethod()
per2=Person.classMethod()
print(per2)

 

try:
    print('normal run')
except KeyError:
    print('key error ...')
else:
    print('程序未产生异常时执行else代码块')
finally:
    print('不管程序是否产生异常都会执行finally代码块')


def fun_try_except():
    try:
        print('normal run')
        print(1/0)
        return 1
    except Exception as e:
        print('key error ...')
        return 2
    else:
        print('程序未产生异常时执行else代码块')
        return 3
    finally:
        print('不管程序是否产生异常都会执行finally代码块')
        #return 4
ret=fun_try_except() ##如果finally出现 return返回值不管程序有无异常结果都为finally代码块返回值 4  若finally代码块没有return返回值 若程序无异常则结果为 1 有异常结果为2
print(ret)

 

import contextlib
class Sample:
    def __enter__(self):
        print("————enter---")
        return self
    def __exit__(self,exc_type,exc_val,exc_tb):
        print("————exit---")
    def run(self):
        print('run.....')
with Sample() as sample:
    sample.run()
@contextlib.contextmanager
def open_file(filename):
    print(f'open {filename}')
    yield {'name':'howhy'}
    print(f'close {filename}')

with open_file('aa.txt') as fr:
    print(fr)
    print('run')

##结果
# ————enter---
# run.....
# ————exit---
# open aa.txt
# {'name': 'howhy'}
# run
# close aa.txt

 

class NumGroup:
    def __init__(self,group_name,nums:list):
        self.group_name=group_name
        self.nums=nums
    def __getitem__(self, item):##切片最重要的方法
        print('__getitem__')
        return self.nums[item]
    def __reversed__(self): ##reversed()
        print('__reversed__')
        self.nums.reverse()
        return self.nums
    def __len__(self):  
        print('__len__')
        return len(self.nums)
    def __iter__(self):
        print('__iter__')
        return iter(self.nums)
    def __contains__(self, item):
        print('__contains__',self.nums.index(item))
        return item in self.nums
numgroups=NumGroup('num',[5,3,2,1,9])
print(numgroups[::-1])
print(len(numgroups))
print(2 in numgroups)
print(reversed(numgroups))
for num in numgroups:
    print(num)

 

posted @ 2023-07-19 10:06  howhy  阅读(15)  评论(0编辑  收藏  举报