>>> brand = ['李宁','耐克','阿迪达斯','鱼']
>>> slogan = ['一切皆有可能','just do it','impossible is nothing ','让编程改变世界']
>>> print ('鱼的口号是',slogan[brand.index('鱼')])
鱼的口号是 让编程改变世界
>>> dict1={
'李宁':'一切皆有可能','耐克':'just do it','阿迪达斯':'impossible is nothing ','鱼':'让编程改变世界'}
>>> print('鱼的口号是',dict1['鱼'])
鱼的口号是 让编程改变世界
>>> dict2 = {
1:'one',2,'two',3,'three'}
SyntaxError: invalid syntax
>>> dict2 = {
1:'one',2:'two',3:'three'}
>>> dict2[2]
'two'
>>> dict3 = {
}
>>> dict3
{
}
>>> help(dict)
Help on class dict in module builtins:
class dict(object)
| dict() -> new empty dictionary
| dict(mapping) -> new dictionary initialized from a mapping object's
| (key, value) pairs
| dict(iterable) -> new dictionary initialized as if via:
| d = {
}
| for k, v in iterable:
| d[k] = v
| dict(**kwargs) -> new dictionary initialized with the name=value pairs
| in the keyword argument list. For example: dict(one=1, two=2)
|
| Methods defined here:
|
| __contains__(self, key, /)
| True if D has a key k, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(...)
| x.__getitem__(y) <==> x[y]
|
| __gt__(self, value, /)
| Return self>value.
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| __repr__(self, /)
| Return repr(self).
|
| __setitem__(self, key, value, /)
| Set self[key] to value.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| fromkeys(iterable, value=None, /) from builtins.type
| Returns a new dict with keys from iterable and values equal to value.
|
| get(...)
| D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
| If key is not found, d is returned if given, otherwise KeyError is raised
|
| popitem(...)
| D.popitem() -> (k, v), remove and return some (key, value) pair as a
| 2-tuple; but raise KeyError if D is empty.
|
| setdefault(...)
| D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __hash__ = None
>>> dict3 = dict((('F',70),('i',105),('h',104),('c',67)))
>>> dict3
{
'F': 70, 'i': 105, 'h': 104, 'c': 67}
>>> dict4=(小甲鱼='让编程改变世界',苍井空='让AV征服')
SyntaxError: invalid syntax
>>>
KeyboardInterrupt
>>> dict4=(小甲鱼='让编程改变世界',苍井空='让AV征服')
SyntaxError: invalid syntax
>>>
KeyboardInterrupt
>>> dict4=(小甲鱼='让编程改变世界',苍井空='让AV征服')
SyntaxError: invalid syntax
>>> dict4=dict(小甲鱼='让编程改变世界',苍井空='让AV征服')
>>> dict4
{
'小甲鱼': '让编程改变世界', '苍井空': '让AV征服'}
>>> dict4['苍井空']='学习编程'
>>> dict4
{
'小甲鱼': '让编程改变世界', '苍井空': '学习编程'}
>>> dict4['爱迪生']= '天才'
>>> dict4
{
'小甲鱼': '让编程改变世界', '苍井空': '学习编程', '爱迪生': '天才'}
>>>
>>> import random
>>> secret =random.randint (1,10)
>>> secret
6
>>> import os
>>> os.getcwd()
'C:\\Users\\MR\\AppData\\Local\\Programs\\Python\\Python36'
>>> os.chdir("E:")
>>> od.listdir("E:")
Traceback (most recent call last):
File "" , line 1, in <module>
od.listdir("E:")
NameError: name 'od' is not defined
>>> os.listdir("E:")
['$RECYCLE.BIN', '360Downloads', '360驱动大师目录', 'code', 'Debug', 'Drivers', 'jianguoyun', 'Manual', 'QQMusicCache', 'record.txt', 'System Volume Information', 'test.txt', 'test_1.py.txt', '图片', '迅雷下载']
>>> os.dir("E:\\A")
Traceback (most recent call last):
File "" , line 1, in <module>
os.dir("E:\\A")
AttributeError: module 'os' has no attribute 'dir'
>>> os.mkdir("E:\\A")
>>> os.mkdir("E:\\A\\B")
>>> os.mkdir("E:\\C\\B")
Traceback (most recent call last):
File "" , line 1, in <module>
os.mkdir("E:\\C\\B")
FileNotFoundError: [WinError 3] 系统找不到指定的路径。: 'E:\\C\\B'
>>> os.rmdir("E:\\A\\B")
Traceback (most recent call last):
File "" , line 1, in <module>
os.rmdir("E:\\A\\B")
OSError: [WinError 145] 目录不是空的。: 'E:\\A\\B'
>>> os.remove("E:\\A\\B\\test.txt")
>>> os.rmdir("E:\\A\\B")
>>> os.system('cmd')
-1073741510
>>> os.system('calc')
0
>>> os.curdir
'.'
>>> os.listdir(os.curdir)
['$RECYCLE.BIN', '360Downloads', '360驱动大师目录', 'A', 'code', 'Debug', 'Drivers', 'jianguoyun', 'Manual', 'QQMusicCache', 'record.txt', 'System Volume Information', 'test.txt', 'test_1.py.txt', '图片', '迅雷下载']
>>> os.path.basename('E:\\A\\B\\C\\sexy.avi')
'sexy.avi'
>>> os.path.dirname('E:\\A\\B\\C\\sexy.avi')
'E:\\A\\B\\C'
>>> os.path.join('A','B','C')
'A\\B\\C'
>>> os.path.join('C:','A','B','C')
'C:A\\B\\C'
>>> os.path.join('C:\\','A','B','C')
'C:\\A\\B\\C'
>>> os.path.split('E:\\A\\B\\C')
('E:\\A\\B', 'C')
>>> os.path.split('E:\\A\\B\\C\\test.avi')
KeyboardInterrupt
>>> os.path.split('E:\\A\\B\\C\\test.avi')
('E:\\A\\B\\C', 'test.avi')
>>> os.path.splitext('E:\\A\\B\\C\\test.avi')
('E:\\A\\B\\C\\test', '.avi')
>>> os.path.getatime('E:\\test.txt')
1601964171.0347624
>>> import time
>>> time.gmtime (os.path.getatime('E:\\test.txt'))
time.struct_time(tm_year=2020, tm_mon=10, tm_mday=6, tm_hour=6, tm_min=2, tm_sec=51, tm_wday=1, tm_yday=280, tm_isdst=0)
>>> time.localtime (os.path.getatime('E:\\test.txt'))
time.struct_time(tm_year=2020, tm_mon=10, tm_mday=6, tm_hour=14, tm_min=2, tm_sec=51, tm_wday=1, tm_yday=280, tm_isdst=0)
>>> time.localtime (os.path.getmtime('E:\\test.txt'))
time.struct_time(tm_year=2020, tm_mon=10, tm_mday=6, tm_hour=14, tm_min=2, tm_sec=51, tm_wday=1, tm_yday=280, tm_isdst=0)
>>> time.localtime (os.path.getctime('E:\\test.txt'))
time.struct_time(tm_year=2020, tm_mon=10, tm_mday=6, tm_hour=13, tm_min=15, tm_sec=14, tm_wday=1, tm_yday=280, tm_isdst=0)
>>> E:\\A\\B\\TEST.TXT
SyntaxError: unexpected character after line continuation character
>>> E:\\A\\B\\TEST.TXT
SyntaxError: unexpected character after line continuation character
>>> E:\\A\\B\\TEST.txt
SyntaxError: unexpected character after line continuation character
>>> 'E:\\A\\B\\TEST.TXT'
'E:\\A\\B\\TEST.TXT'
>>> os.path.ismount('E:\\')
True
>>> os.path.ismount('E:\\A')
False
>>>
>>> import pickle
>>> my_list =[123,3.14,'xiaojiayu',['xnother list']]
>>> pickle_file = open("my_list.pkl",'wb')
>>> pickle.dump(my_list,pickle_file)
>>> pickle_file.close()
>>> pickle_file = open("my_list.pkl",'rb')
>>> my_list2 = pickle.load(pickle_file)
>>> print(my_list2)
[123, 3.14, 'xiaojiayu', ['xnother list']]
file_name = input('请输入需要打开的文件名:')
f = open(file_name,encoding='utf-8')
print('文件的内容是:')
for each_line in f:
print(each_line)
常见报错类型:
>>> my_list = ['小甲鱼是帅哥']
>>> assert len(my_list) > 0
>>> my_list.pop()
'小甲鱼是帅哥'
>>> assert len(my_list) >0
Traceback (most recent call last):
File "" , line 1, in <module>
assert len(my_list) >0
AssertionError
>>> my_list.fishc
Traceback (most recent call last):
File "" , line 1, in <module>
my_list.fishc
AttributeError: 'list' object has no attribute 'fishc'
>>> my_list = [1,2,3]
>>> my_liat[3]
Traceback (most recent call last):
File "" , line 1, in <module>
my_liat[3]
NameError: name 'my_liat' is not defined
>>> my_list[2]
3
>>> my_dixt = {
'one' : 1,'two':2,'three':3}
>>> my_dict["one"]
Traceback (most recent call last):
File "" , line 1, in <module>
my_dict["one"]
NameError: name 'my_dict' is not defined
>>> my_dict['one']
Traceback (most recent call last):
File "" , line 1, in <module>
my_dict['one']
NameError: name 'my_dict' is not defined
>>> my_dixt['one']
1
>>> my_dixt['four']
Traceback (most recent call last):
File "" , line 1, in <module>
my_dixt['four']
KeyError: 'four'
>>> my_dixt.get('four')
>>> my_dixt
{
'one': 1, 'two': 2, 'three': 3}
>>> fishc
Traceback (most recent call last):
File "" , line 1, in <module>
fishc
NameError: name 'fishc' is not defined
>>> print'i love'
SyntaxError: invalid syntax
>>> 1+'1'
Traceback (most recent call last):
File "" , line 1, in <module>
1+'1'
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> 7/0
Traceback (most recent call last):
File "" , line 1, in <module>
7/0
ZeroDivisionError: division by zero
>>>
try:
# int('abc')
sum = 1 + '1'
f = open('我为什么是一个文件.txt','r',encoding='utf-8')
print(f.read())
f.close()
except OSError as reason:
print('文件出错啦\n错误的原因是'+str(reason))
except TypeError as reason:
print('类型出错啦\n错误的原因是'+str(reason))
try:
#int('abc')
f = open('我为什么是一个文件.txt','w',encoding='utf-8')
print(f.write('我存在了'))
sum = 1 + '1'
except OSError as reason:
print('文件出错啦\n错误的原因是'+str(reason))
except TypeError as reason:
print('类型出错啦\n错误的原因是'+str(reason))
finally:
f.close()
>>> 7/0
Traceback (most recent call last):
File "" , line 1, in <module>
7/0
ZeroDivisionError: division by zero
>>> raise ZeroDivisionError('除数为0的异常')
Traceback (most recent call last):
File "" , line 1, in <module>
raise ZeroDivisionError('除数为0的异常')
ZeroDivisionError: 除数为0的异常
如果怎么样就干吧
def showMaxFactor(num):
count = num//2
while count > 1:
if num %count ==0:
print("%d最大的约数是%d"%(num,count))
break
count -= 1
else:
print('%d是素数!'%num)
num = int(input('请输入一个数:'))
showMaxFactor(num)
try:
# int('abc')
int('123')
except ValueError as reason:
print('出错啦'+str(reason))
else:
print('没有任何异常')
# try:
# f =open('data.txt','w',encoding='utf-8')
# for each_line in f:
# print(each_line)
# except OSError as reason:
# print('出错啦'+str(reason))
# finally:
# f.close()
try:
with open('data.txt','w',encoding='utf-8') as f:
for each_line in f:
print(each_line)
except OSError as reason:
print('出错啦'+str(reason))
信了小甲鱼的‘鬼话’,以为要自己下载easygui,一看教程全部要在网上下载Python的工具包easygui-0.96或easygui-0.97,而这个工具包不是要fq到官网下载,就是要付费。。。既然白嫖当然要贯彻到底咯,功夫不负穷孩子,终于找到了一个直接cmd安装的,操作超级简单网址拿走不谢
不过以防万一,附上我的所有骚操作,害怕疏漏,我是先安装的pycharm中的easygui最后直接命令行接着上面网址的输入pip,没有下载pip,就显示已有。
就大功告成了,不知道有没有关系
pycharm中easygui安装的方法
file->settings->project:->project interpreter
右侧加号+
搜索 easygui,点击instal安装即可
import easygui as g
import sys
while 1:
g.msgbox('hi,欢迎进入第一个界面小游戏')
msg = '请问你希望在工作室学到什么知识呀?'
title = '小游戏互动'
choices = ['谈恋爱','编程','emm','琴棋书画']
choice = g.choicebox(msg,title,choices)
#note that we convert choice to string, in case
#the user canceled the choice, and we got none.
g.msgbox('你的选择是:'+str(choice),'结果')
msg = '你希望重新开始小游戏吗'
title = '请选择'
if g.ccbox(msg,title): #show a continue/cancel dialog
pass #user chose continue
else:
sys.exit(0)#user chose cancel
对象= 属性+方法
class Turtle:#python 中的类名约定以大写字母开头
# ===关于类的一个简单例子===
#属性
color = 'green'
weight = 10
legs = 4
shell = True
mouth = '大嘴'
#方法
def climb(self):
print('我正在努力的向前爬')
def run(self):
print('我正在飞快的向前跑')
def bite(self):
print('咬死你')
def eat(self):
print('有的吃满足。。')
def sleep(self):
print('困了')
>>> import turtle
>>> tt = Turtle()
Traceback (most recent call last):
File "" , line 1, in <module>
tt = Turtle()
NameError: name 'Turtle' is not defined
>>> tt = Turtle()
Traceback (most recent call last):
File "" , line 1, in <module>
tt = Turtle()
NameError: name 'Turtle' is not defined
>>> Turtle()
Traceback (most recent call last):
File "" , line 1, in <module>
Turtle()
NameError: name 'Turtle' is not defined
>>> Turtle().climb()
Traceback (most recent call last):
File "" , line 1, in <module>
Turtle().climb()
NameError: name 'Turtle' is not defined
>>> import Turtle
Traceback (most recent call last):
File "" , line 1, in <module>
import Turtle
ModuleNotFoundError: No module named 'Turtle'
>>> import turtle
>>> tt = turtle()
Traceback (most recent call last):
File "" , line 1, in <module>
tt = turtle()
TypeError: 'module' object is not callable
>>>
=== RESTART: C:/Users/MR/AppData/Local/Programs/Python/Python36/xjy036.py ===
>>> tt = Turtle()
>>> Turtle()
<__main__.Turtle object at 0x00000210B04396A0>
>>> tt.climb()
我正在努力的向前爬
>>> tt.bite()
咬死你
>>> tt.sleep()
困了
>>>
我可能就是传说中的憨憨本人了,这个地方小甲鱼明明是运行了第一个Turtle()文件,我以为他是在交互页面,害,听课不积极,早晚出问题。
继承
>>> list1=[2,1,3,5,7]
>>> list.sort()
Traceback (most recent call last):
File "" , line 1, in <module>
list.sort()
TypeError: descriptor 'sort' of 'list' object needs an argument
>>> list1.sort()
>>> list1
[1, 2, 3, 5, 7]
>>> list1.append(9)
>>> liat1
Traceback (most recent call last):
File "" , line 1, in <module>
liat1
NameError: name 'liat1' is not defined
>>> list1
[1, 2, 3, 5, 7, 9]
>>> class Mylist(list):
pass
>>> list2 = Mylist()
>>> list2.append(5)
>>> list2
[5]
>>> list2.append(2)
>>> list.sort()#排序
Traceback (most recent call last):
File "" , line 1, in <module>
list.sort()
TypeError: descriptor 'sort' of 'list' object needs an argument
>>> list2.sort()
>>> list2
[2, 5]
多态:不同对象对同一方法响应不同的行动
>>> class A:
def fun(self):
print('我是小啊')
>>> class B:
def fun(self):
print('我是小兵')
>>> a=A()
>>> b=B()
>>> a.fun()
我是小啊
>>> a.fun()
我是小啊
>>> b.fun()
我是小兵
>>>
self是什么?
>>> class Ball:
def setName(self, name):
self.name = name
def kick(self):
print("我叫%s,该死的,谁踢我"% self.name)
>>> a= Ball()
>>> a.setName('球a')
>>> a.kick()
我叫球a,该死的,谁踢我
__init__(self,param1,param2...)
>>> class Ball:
def __init__(self,name):
self.name = name
def kick(self):
print("我叫%s,该死的,谁踢我"% self.name)
>>> b=Ball('tomato')
>>> b.kick()
我叫tomato,该死的,谁踢我
>>>
>>> class Person:
name = '小甲鱼'
>>> p = Person()
>>> p,name
Traceback (most recent call last):
File "" , line 1, in <module>
p,name
NameError: name 'name' is not defined
>>> p.name()
Traceback (most recent call last):
File "" , line 1, in <module>
p.name()
TypeError: 'str' object is not callable
>>> p.name
'小甲鱼'
>>> class Person:
__name = '小甲鱼'#公有变私有
>>> p = Person()
>>> p.name
Traceback (most recent call last):
File "" , line 1, in <module>
p.name
AttributeError: 'Person' object has no attribute 'name'
>>> class Person:
__name = '小甲鱼'
def getName(self):
return self._name#应该是双下划线
>>> p=Person()
>>> p.name
Traceback (most recent call last):
File "" , line 1, in <module>
p.name
AttributeError: 'Person' object has no attribute 'name'
>>> p.getName()
Traceback (most recent call last):
File "" , line 1, in <module>
p.getName()
File "" , line 4, in getName
return self._name
AttributeError: 'Person' object has no attribute '_name'
>>> class Person:
__name = '小甲鱼'
def getName(self):
return self.__name
>>> p = Person()
>>> p.name
Traceback (most recent call last):
File "" , line 1, in <module>
p.name
AttributeError: 'Person' object has no attribute 'name'
>>> p.getName()
'小甲鱼'
>>> p._Person__name
'小甲鱼'
class DerivedClassName(BaseClassName):
import random as r
class Fish:
def __init__(self):
self.x = r.randint(0,10)
self.y = r.randint(0,10)
def move(self):
self.x -= 1
print('我的位置是', self.x,self.y)
class Goldfish(Fish):
pass
class Carp(Fish):
pass
class Salmon(Fish):
pass
class Shark(Fish):
def __init__(self):
self.hungry = True
def eat(self):
if self.hungry:
print('吃货的梦想天天有的吃')
self.hungry =False
else:
print('太撑了吃不下')
>>> fish = Fish()
>>> fish.move()
我的位置是 8 7
>>> fish.move()
我的位置是 7 7
>>> goldfish=Goldfish()
>>> goldfish.move()
我的位置是 6 4
>>> gildfish.move()
Traceback (most recent call last):
File "" , line 1, in <module>
gildfish.move()
NameError: name 'gildfish' is not defined
>>> goldfish.move()
我的位置是 5 4
>>> shark = Shark()
>>> shark.eat()
吃货的梦想天天有的吃
>>> shark.eat()
太撑了吃不下
>>> shark.move()
Traceback (most recent call last):
File "" , line 1, in <module>
shark.move()
File "C:/Users/MR/AppData/Local/Programs/Python/Python36/xjy038.py", line 10, in move
self.x -= 1
AttributeError: 'Shark' object has no attribute 'x'
>>>
发现shark位置函数报错,原因是子类将父类函数覆盖了,改进方法:
import random as r
class Fish:
def __init__(self):
self.x = r.randint(0,10)
self.y = r.randint(0,10)
def move(self):
self.x -= 1
print('我的位置是', self.x,self.y)
class Goldfish(Fish):
pass
class Carp(Fish):
pass
class Salmon(Fish):
pass
class Shark(Fish):
def __init__(self):
# Fish.__init__(self)
super().__init__()
self.hungry = True
def eat(self):
if self.hungry:
print('吃货的梦想天天有的吃')
self.hungry =False
else:
print('太撑了吃不下')
运行结果
=== RESTART: C:/Users/MR/AppData/Local/Programs/Python/Python36/xjy038.py ===
>>> shark = Shark()
>>> shark.move()
我的位置是 1 4
>>> Fish.__init__(shark)
>>> shark.move()
我的位置是 0 0
>>> Fish.__init__()
Traceback (most recent call last):
File "" , line 1, in <module>
Fish.__init__()
TypeError: __init__() missing 1 required positional argument: 'self'
>>>
=== RESTART: C:/Users/MR/AppData/Local/Programs/Python/Python36/xjy038.py ===
>>> shark = Shark()
Traceback (most recent call last):
File "" , line 1, in <module>
shark = Shark()
File "C:/Users/MR/AppData/Local/Programs/Python/Python36/xjy038.py", line 23, in __init__
super()>__init__()
NameError: name '__init__' is not defined
>>>
=== RESTART: C:/Users/MR/AppData/Local/Programs/Python/Python36/xjy038.py ===
>>> shark = Shark()
>>> shark.move()
>>> class Base1:
def fool(self):
print("我是fool,我为Base1代言")
>>> class Base2:
def foo2(self):
print("我是foo2,我为Base2代言")
>>> class C(Base1,Base2):
pass
>>> c=C()
>>> c.fool()
我是fool,我为Base1代言
>>> c.foo2()
我是foo2,我为Base2代言
组合
案例:
class Turtle:
def __init__(self,x):
self.num = x
class Fish:
def __init__(self,x):
self.num = x
class Pool:
def __init__(self,x,y):
self.turtle = Turtle(x)
self.fish = Fish(y)
def print_num(self):
print("水池里总共有乌龟%d 只,鱼 %d 条"%(self.turtle.num,self.fish.num))
输出:
=== RESTART: C:/Users/MR/AppData/Local/Programs/Python/Python36/xjy039.py ===
>>> pool = Pool(1,10)
>>> pool.print_num()
水池里总共有乌龟1 只,鱼 10 条
类、类对象和实例对象
>>> class C:
count = 0
>>> a=C()
>>> b=C()
>>> c=C()
>>> a.count
0
>>> b.count
0
>>> c.count
0
>>> c.count += 10
>>> c.count
10
>>> a.count
0
>>> b.count
0
>>> C.count
0
>>> C.count += 10
>>> a.count
10
>>> C.count = 100
>>> a.count
100
>>> b.count
100
>>> c.count
10
>>> class C:
def x(self):
print("X-man")
>>> c=C()
>>> c.x()
X-man
>>> c.x=1
>>> c.x
1
>>> c.x()
Traceback (most recent call last):
File "" , line 1, in <module>
c.x()
TypeError: 'int' object is not callable
>>> class BB:
def printBB():
print('no zuo no die')
>>> BB.printBB()
no zuo no die
>>> bb = BB()
>>> bb.printBB()
Traceback (most recent call last):
File "" , line 1, in <module>
bb.printBB()
TypeError: printBB() takes 0 positional arguments but 1 was given
>>> class CC:
def setXY(self, x, y):
self.x = x
self.y = y
def printXY(self):
print(self.x,self.y)
>>> dd = CC()
>>> dd.__dict__
{
}
>>> CC.__dict__
mappingproxy({
'__module__': '__main__', 'setXY': <function CC.setXY at 0x0000022AB8990510>, 'printXY': <function CC.printXY at 0x0000022AB8990598>, '__dict__': <attribute '__dict__' of 'CC' objects>, '__weakref__': <attribute '__weakref__' of 'CC' objects>, '__doc__': None})
>>> dd.setXY(4,5)
>>> dd.__dict__
{
'x': 4, 'y': 5}
>>> CC.__dict__
mappingproxy({
'__module__': '__main__', 'setXY': <function CC.setXY at 0x0000022AB8990510>, 'printXY': <function CC.printXY at 0x0000022AB8990598>, '__dict__': <attribute '__dict__' of 'CC' objects>, '__weakref__': <attribute '__weakref__' of 'CC' objects>, '__doc__': None})
>>> del CC
>>> ee = CC()
Traceback (most recent call last):
File "" , line 1, in <module>
ee = CC()
NameError: name 'CC' is not defined
>>> dd.printXY()
4 5
>>>
#issubclass()
>>> class A:
pass
>>> class B(A):
pass
>>> issubclass(B,A)
True
>>> issubclass(B,B)
True
>>> issubclass(B,object)
True
>>> class C:
pass
>>> issubclass(B,C)
False
#isinstance(object,classinfo)
>>> b1=B()
>>> isinstance(b1,B)
True
>>> isinstance(b1,A)
True
>>> isinstance(b1,C)
False
>>> isinstance(b1,(A,B,C))
True
#hasattr(object,name)用于判断对象是否包含对应的属性
>>> def __init__(self,x=0):
self.x = x
>>> c1=C()
>>> hasattr(c1,x)
Traceback (most recent call last):
File "" , line 1, in <module>
hasattr(c1,x)
NameError: name 'x' is not defined
>>> hasattr(c1,'x')
True
#getattr(object,name[,default])
>>> getattr(c1,'x')
0
>>> getattr(c1,'y')
Traceback (most recent call last):
File "" , line 1, in <module>
getattr(c1,'y')
AttributeError: 'C' object has no attribute 'y'
>>> getattr(c1,'y','您所访问的属性不存在')
'您所访问的属性不存在'
#setattr(object,name,value)
#delattr(object,name)
>>> setattr(c1,'y','fishc')
>>> getattr(c1,'y','您所访问的属性不存在')
'fishc'
>>> delattr(c1,'y')
>>>
>>> getattr(c1,'y','您所访问的属性不存在')
'您所访问的属性不存在'
>>> class C:
def __init__(self,size = 10):
self.size = size
def getSize(self):
return self.size
def setSize(self,value):
self.size = value
def delSize(self):
del self.size
x = property(getSize,setSize,delSize)
>>> cl = C()
>>> c1.getSize()
Traceback (most recent call last):
File "" , line 1, in <module>
c1.getSize()
AttributeError: 'C' object has no attribute 'getSize'
>>> c1=C()
>>> c1.getSize()
10
>>> c1.x
10
>>> c1.x = 18
>>> c1.x
18
>>> c1.size
18
>>> c1.getSize()
18
>>> del c1.x
>>> c1.size
Traceback (most recent call last):
File "" , line 1, in <module>
c1.size
AttributeError: 'C' object has no attribute 'size'
>>>
魔法方法总是被双下划线包围,例如__init__
#__init__(self[,...])