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))
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>
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'))