2020-12-12


我的python版本 3.8,不同版本的python可能有影响。

一切皆对象

验证函数和类都是对象。
思路:定义一个函数和类,使用isinstance()函数来判断函数和类是否是对象。

def func():    #定义一个函数
    return None

class Func(): #定义一个类
    def __init__(self,name='xxx'):
        self.name = name

    def func_demo(self):  #定义实例的方法
        print(self.name)
        return self.name

if __name__ == '__main__':
    my_func=func
    print(isinstance(my_func,object))  #True
    my_Func=Func()
    print(isinstance(my_Func,object)) #True
    print(isinstance(my_Func.func_demo,object)) #True

魔法方法__getitem__

#__getitem__使对象实现迭代功能。

a = ['我','与','秋','风','皆','过','客']
class A(object):
    def __init__(self,args):
        self.list = args

    def __getitem__(self, item):
        print(item)
        return self.list[item]

li=A(a)
for i in li:
    print(i)

魔法方法之__str__和__repr__

  • __repr__和__str__这两个方法都是用于显示的,__str__是面向用户的,而__repr__面向程序员。
class A(object):
    def __init__(self,name):
        self.name=name
        
a=A('lh')
print(a)
print(a.__repr__()) 
print(a.__str__())

在这里插入图片描述
我们发现__repr__和__str__返回的都是对象所在的内存地址,这时我们需要对__repr__和__str__重写。

#重写__repr__方法
class A(object):
    def __init__(self,name):
        self.name=name

    def __repr__(self):
        return "{name:%s}" %self.name

在这里插入图片描述

#重写__str__方法
class A(object):
    def __init__(self,name):
        self.name=name

    def __str__(self):
        return "{name:%s}" %self.name
 a=A('lh')

在这里插入图片描述

多态

  • extend方法
a = [1,2,3]
b = {4,5}
c= (6,7)
a.extend(b)
print(a)
a.extend(c)
print(a) 

#[1, 2, 3, 4, 5]
#[1, 2, 3, 4, 5, 6, 7]
  • 不同类的同种方法调用
class Dog(object):
    def eat(self):
        print('狗吃狗粮')

class Cat(object):
    def eat(self):
        print('猫吃猫粮')

class Fish(object):
    def eat(self):
        print('鱼吃饵料')

animals= [Dog,Cat,Fish]

for animal in animals:
    animal().eat()

#狗吃狗粮
#猫吃猫粮
#鱼吃饵料

type与isinstance

type和isinstance都是判断对象的类型,不同的是type判断对象类型时不会考虑继承关系,而isinstance判断对象的类型时会考虑继承关系。

class A(object):
    pass

class B(A):
    pass

a = A()
b = B()

print(type(a) is A)   #True
print(type(b) is B)   #True
print(type(b) is A)   #False
print(isinstance(a,A))  #True
print(isinstance(b,B))  #True
print(isinstance(b,A))  #True

类属性与实例属性

#@Time          : 2020/12/12下午 01:55
#@Author        : Anthony.l
#@File          :instance_attribute-and-class_attribute.py
#@Software      :PyCharm


class A(object):
    title1 = '这是类属性'
    def __init__(self):
        self.title2 = '这是实例属性'


class B(A):
    pass

a = A()
b = B()
print(a.title1)
print(a.title2)
print('~~~~~~~~~~')
print(b.title1)
print(b.title2)
print('~~~~~~~~~~~')
print(A.title1)
# print(A.title2)

#这是类属性
#这是实例属性
#~~~~~~~~~~
#这是类属性
#这是实例属性
#~~~~~~~~~~~
#这是类属性

我们发现当实例没有属性时会向上类中去搜寻属性,若类中没有属性则会报错;但是类中没有属性,不会向下寻找属性,而是直接报错。

继承的拓展

类的继承,有两种算法:
1、深度优先搜索DFS

class A(object):
    pass

class B(object):
    pass

class C(A):
    pass

class D(B):
    pass

class E(C,D):
    pass

print(E.__mro__)

#(<class '__main__.E'>, <class '__main__.C'>, <class '__main__.A'>, <class '__main__.D'>, <class '__main__.B'>, <class 'object'>)

2.广度优先搜索BFS

class A(object):
    pass

class B(A):
    pass

class C(A):
    pass

class D(B,C):
    pass

print(D.__mro__)

#(<class '__main__.E'>, <class '__main__.D'>, <class '__main__.B'>, <class '__main__.A'>, <class 'object'>)

实例方法、类方法与静态方法

class Data(object):
    def __init__(self,year,month,day):
        self.year = year
        self.month = month
        self.day = day
	
	#实例方法
    def tomorrow(self):
        self.day += 1

	#静态方法
    @staticmethod 
    def parse_from_string(data):
        year, month, day = data.split('-')
        return (int(year),int(month),int(day))
    
    #类方法
    @classmethod
    def get_day(cls,data):
        year, month, day = data.split('-')
        return cls(int(year), int(month), int(day))
	
	#重写repr方法
    def __repr__(self):
        return "%s %s %s" %(self.year,self.month,self.day)
        
if __name__ == '__main__':
    day = Data(2020,12,12)
    print(day.tomorrow()) #调用实例方法

    date = '2020-12-12'
    print(Data.parse_from_string(date)) #调用静态方法
    print(Data.get_day(date)) #调用类方法

super函数

获取父类的属性

class Person(object):
    def __init__(self,name,age,sex,weight):
        self.name = name
        self.age = age
        self.sex = sex
        self.weight = weight


class Student(Person):
    def __init__(self,name,age,sex,weight,grade):
        super().__init__(name,age,sex,weight)
        self.grade = grade
        
    def __repr__(self):
        return "name:%s\nage:%s\nsex:%s\nweight:%s\ngrade:%s"%(self.name,self.age,self.sex,self.weight,self.grade)

student=Student('lh','18','male','60kg',12)
print(student)

在这里插入图片描述
查看继承属性

class A(object):
    def __init__(self):
        print('A')

class B(A):
    def __init__(self):
        print('B')
        super().__init__()

class C(A):
    def __init__(self):
        print("C")
        super().__init__()

class D(B,C):
    def __int__(self):
        print("D")
        super().__init__()

print(D.__mro__)
#D->B->C->A  广度优先搜索BFS

自省

  • 计算机编程中,自省是指这种能力:检查某些事物以确定它是什么、它知道什么以及它能做什么。自省向程序员提供了极大的灵活性和控制力。

  • Python中比较常见的自省(introspection)机制(函数用法)有: dir(),type(), hasattr(), isinstance(),通过这些函数,我们能够在程序运行时得知对象的类型,判断对象是否存在某个属性,访问对象的属性。

  • dir()

    • 返回传递给它的任何对象的属性名称经过排序的列表。
    class A():
    	pass
    print(dir(A))
    #['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
    
  • type()

  • 通过返回类型对象来确定对象是字符串还是整数,或是其它类型的对象.
print(type(11))
#<class 'int'>
  • hasattr()
  • 测试一个或多个属性是否存在.
  • isinstance()
  • 测试对象,以确定它是否是某个特定类型或定制类的实例。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值