TypeError: 'builtin_function_or_method' object has no attribute '__getitem__'

本文详细解释了在使用内置函数时出现的错误信息,指出错误通常源于符号写法错误,并通过示例说明如何避免此类问题。


谷歌下的翻译是:内置函数或方法对象没有获取项目属性


错误的是在内置的函数中符号写错。


例如 range(1,5) 写成 range[1,5]


8.4 继 承 #! /usr/bin/python3 # -*- coding:UTF-8 -*- class Animal(object): def run(self): print('Animal is running...') class Dog(Animal): pass class Cat(Animal): pass dog = Dog() dog.run() cat = Cat() cat.run() 执行结果: Animal is running... Animal is running... #! /usr/bin/python3 # -*- coding:UTF-8 -*- class Dog(Animal): def eat(self): print('Eating ...') dog = Dog() dog.run() dog.eat() 执行结果: Animal is running... Eating ... #! /usr/bin/python3 # -*- coding:UTF-8 -*- class Animal(object): def run(self): print('Animal is running...') def __run(self): print('I am a private method.') 执行语句: dog = Dog() dog.__run() 执行结果: Traceback (most recent call last): File "D:/python/workspace/classextend.py", line 25, in <module> dog.__run() AttributeError: 'Dog' object has no attribute '__run' class Animal(object): def run(self): print('Animal is running...') def jump(self): print('Animal is jumpping....') def __run(self): print('I am a private method.') dog = Dog() dog.run() dog.jump() cat = Cat() cat.run() cat.jump() 执行结果: Animal is running... Animal is jumpping.... Animal is running... Animal is jumpping.... 8.5 多 态 #! /usr/bin/python3 # -*- coding:UTF-8 -*- class Dog(Animal): def run(self): print('Dog is running...') class Cat(Animal): def run(self): print('Cat is running...') 执行语句: dog = Dog() print('实例化Dog类') dog.run() cat = Cat() print('实例化Cat类') cat.run() 执行结果: 实例化Dog类 Dog is running... 实例化Cat类 Cat is running... a = list() # a是list类型 b = Animal() # b是Animal类型 c = Dog() # c是Dog类型 print('a是否为list类型:', isinstance(a, list)) print('b是否为Animal类型:', isinstance(b, Animal)) print('c是否为Dog类型:', isinstance(c, Dog)) 执行结果: a是否为list类型: True b是否为Animal类型: True c是否为Dog类型: True print('c是否为Dog类型:', isinstance(c, Dog)) print('c是否为Animal类型:',isinstance(c, Animal)) 执行结果: c是否为Dog类型: True c是否为Animal类型: True #! /usr/bin/python3 # -*- coding:UTF-8 -*- def run_two_times(animal): animal.run() animal.run() run_two_times(Animal()) 执行结果: Animal is running... Animal is running... run_two_times(Dog()) 执行结果: Dog is running... Dog is running... run_two_times(Cat()) 执行结果: Cat is running... Cat is running... #! /usr/bin/python3 # -*- coding:UTF-8 -*- class Bird(Animal): def run(self): print('Bird is flying the sky...') run_two_times(Bird()) 执行结果: Bird is flying the sky... Bird is flying the sky... 8.6 封 装 #! /usr/bin/python3 # -*- coding:UTF-8 -*- class Student(object): def __init__(self, name, score): self.name = name self.score = score std = Student('xiaozhi',90) def info(std): print('学生:%s;分数: %s' % (std.name, std.score)) info(std) 执行结果: 学生:xiaozhi;分数: 90 #! /usr/bin/python3 # -*- coding:UTF-8 -*- class Student0(object): def __init__(self, name, score): self.name = name self.score = score def info(self): print('学生:%s;分数: %s' % (self.name, self.score)) stu = Student0('xiaomeng',95) 执行结果: 学生:xiaomeng;分数: 95 8.7 多重继承 #! /usr/bin/python3 # -*- coding:UTF-8 -*- class Animal(object): pass # 大类: class Mammal(Animal): pass class Bird(Animal): pass # 各种动物: class Dog(Mammal): pass class Bat(Mammal): pass class Parrot(Bird): pass class Ostrich(Bird): pass #! /usr/bin/python3 # -*- coding:UTF-8 -*- class Runnable(object): def run(self): print('Running...') class Flyable(object): def fly(self): print('Flying...') class Dog(Mammal, Runnable): pass class Bat(Mammal, Flyable): pass 8.8 获取对象信息 1. 使用type()函数 >>> type(123) <class 'int'> >>> type('abc') <class 'str'> >>> type(None) <class 'NoneType'> >>> type(abs) <class 'builtin_function_or_method'> >>> type(pri_pub) #上一节定义的PrivatePublicMethod类 <class '__main__.PrivatePublicMethod'> >>> type(123)==type(456) True >>> type(123)==int True >>> type('abc')==type('123') True >>> type('abc')==str True >>> type('abc')==type(123) False >>> import types >>> def func(): ... pass ... >>> type(fn)==types.FunctionType True >>> type(abs)==types.BuiltinFunctionType True >>> type(lambda x: x)==types.LambdaType True >>> type((x for x in range(10)))==types.GeneratorType True 2. 使用isinstance()函数 >>> animal = Animal() >>> dog = Dog() >>> isinstance(dog, Dog) True >>> isinstance(dog, Animal) True >>> isinstance(dog, object) True >>> isinstance(dog, Dog) and isinstance(dog, Animal) True >>> isinstance(animal,Dog ) False >>> isinstance([1, 2, 3], (list, tuple)) True >>> isinstance((1, 2, 3), (list, tuple)) True 3. 使用dir() >>> dir('abc') ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] 8.9 类的专有方法 1. __str__ #! /usr/bin/python3 # -*- coding:UTF-8 -*- class Student(object): def __init__(self, name): self.name = name print(Student('xiaozhi')) 执行结果: <__main__.Student object at 0x0000000000D64198> #! /usr/bin/python3 # -*- coding:UTF-8 -*- class Student(object): def __init__(self, name): self.name = name def __str__(self): return '学生名称: %s' % self.name print(Student('xiaozhi')) 执行结果: 学生名称: xiaozhi >>> s = Student('xiaozhi') >>> s <__main__.Student object at 0x00000000030EC550> #! /usr/bin/python3 # -*- coding:UTF-8 -*- class Student(object): def __init__(self, name): self.name = name def __str__(self): return '学生名称: %s' % self.name __repr__ = __str__ 在交互模式下执行: >>> s = Student('xiaozhi') >>> s 学生名称: xiaozhi 2. __iter__ #! /usr/bin/python3 # -*- coding:UTF-8 -*- class Fib(object): def __init__(self): self.a, self.b = 0, 1 # 初始化两个计数器a、b def __iter__(self): return self # 实例本身就是迭代对象,故返回自己 def __next__(self): self.a, self.b = self.b, self.a + self.b # 计算下一个值 if self.a > 100000: # 退出循环的条件 raise StopIteration(); return self.a # 返回下一个值 3. __getitem__ >>> Fib()[3] Traceback (most recent call last): File "<pyshell#35>", line 1, in <module> Fib()[3] TypeError: 'Fib' object does not support indexing class Fib(object): def __get分段模拟运行结果给出
最新发布
10-22
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值