1、isinstance ,type, issubclass
 
      isinstance:判断给的对象是否是**类型
   
      type:返回**对象的数据类型
 
      issubclass:判断**类是否**的子类
class Animal:
    def eat(self):
        print('动物的世界你不懂')

class Cat(Animal):
    def play(self):
        print('毛霸王')

c = Cat()

print(isinstance(c,Cat))  # True
# 向上判断
print(isinstance(c,Animal)) # True

a = Animal()
print(isinstance(a,Cat))  # False # 不能向下判断

print(type(a))  # <class '__main__.Animal'>
print(type([]))  # <class 'list'>
print(type(c)) # <class '__main__.Cat'>

# 判断 **类是否是**类的子类
print(issubclass(Cat,Animal))  # True
print(issubclass(Animal,Cat)) # False
def cul(a,b):

    if (type(a) == int or type(a) == float) and (type(b) == int or type(b) == float):
        return a+b
    else:
        print('提供的数据无法计算')

print(cul(6,7))
2、如何区分方法和函数
 
  打印结果中包含了function 的为函数,包含method为方法
 
def func():
    print('我是函数')

class Foo:
    def eat(self):
        print('要吃饭了')

print(func)  # <function func at 0x0000020EDE211E18>
f = Foo()
f.eat()

print(f.eat)  # <bound method Foo.eat of <__main__.Foo object at 0x00000237390BE358>>
在类中:
        实例方法
            如果是类名.方法   则为函数
            如果是对象.方法   则为方法
 
           类方法:都是方法
            静态方法:都是函数
# 类也是对象
# 这个对象:属性就是类变量
#         方法就是类方法

class Person():
    def eat(self):
        print('明天去吃鱼')

    @classmethod
    def he(cls):
        print('我是类方法')

    @staticmethod
    def lang():
        print('我是静态方法')

p = Person()
Person.eat(1) # 不符合面向对象的思维

print(p.eat)  # <bound method Person.eat of <__main__.Person object at 0x00000253E992E3C8>>
print(Person.eat)  # <function Person.eat at 0x00000253E992DF28>

# 类方法都是方法
print(Person.he) # <bound method Person.he of <class '__main__.Person'>>
print(p.he) # <bound method Person.he of <class '__main__.Person'>>

# 静态方法都是函数
print(Person.lang)  # <function Person.lang at 0x0000024C942F1158>
print(p.lang)  # <function Person.lang at 0x0000024C942F1158>
  from types import MethodType,FunctionType
    isinstance()
 
3、反射
 
    attr:attributebute
 
    getattr()
        从**对象获取到**属性值
 
    hasattr()
        判断**对象中是否有**属性值
 
    delattr()
        从**对象中删除**属性
 
    setattr()
        设置***对象中的**属性为**值
 
master.py
def eat():
    print('吃遍人间美味')

def travel():
    print('游遍万水千山')

def see():
    print('看遍人间繁华')

def play():
    print('玩玩玩')

def learn():
    print('好好学习天天向上')
import master
while 1:
    content = input('请输入你要测试的功能:')
    # 判断 XXX对象中是否包含了xxx

    if hasattr(master,content):
        s = getattr(master,content)
        s()
        print('有这个功能')
    else:
        print('没有这个功能')

 

class Foo:
    def drink(self):
        print('要少喝酒')

f = Foo()
s = (getattr(f,'drink'))  #  从对象中获取到str属性的值
s()
print(hasattr(f,'eat'))   # 判断对象中是否包含str属性
setattr(f,'eat','西瓜')    #  把对象中的str属性设置为value
print(f.eat)
setattr(f,'eat',lambda x:x+1)
print(f.eat(3))
print(f.eat)              # 把str属性从对象中删除
delattr(f,"eat")
print(hasattr(f,'eat'))

 

posted on 2018-12-21 15:25  古鲁月  阅读(103)  评论(0编辑  收藏  举报