您的位置:首页 > 编程语言 > Python开发

[python自学笔记]python基础

2018-01-29 22:58 435 查看
1、python3数据类型

  用type(var)来检测变量var是什么类型,用isinstance(var, type)用来检测var变量是否为type类型

数字型Number(int, long, float, complex)

布尔型bool

字符串str

列表list

元组tuple

字典dict(全称dictionary)

集合set

a, b, c, d = 20, 5.5, True, 4+3j
print(type(a), type(b), type(c), type(d))
print(isinstance(a,int))
a = [1,2,3]
b = (1,2,3)
c = {"name":"小明", "age": 10}
d = {1,2,3} #也可以d = set([1, 2, 3])
print(type(a), type(b), type(c), type(d))
e = "helloworld"
print(type(e))


输出结果:

<type 'int'> <type 'float'> <type 'bool'> <type 'complex'>
True
<type 'list'> <type 'tuple'> <type 'dict'> <type 'set'>
<type 'str'>


2、python3 运算符

加+

减-

乘*(乘字符串代表字符串重复
4000
多少次)

除/

取整除//

取余%

幂运算**

print(2 + 3)
print(2.2 + 5j - 3j)
print(2.3 * 6)
print(3 / 2)
print(3 // 2)
print(3 % 2)
print(2**3)
print("="*5)


输出结果:

5
2.2 + 2j
13.799999
1.5
1
1
8
=====


3、数据类型转换

函数                       说明
int(x [,base ])     将x转换为一个整数
long(x [,base ])    将x转换为一个长整数
float(x )           将x转换到一个浮点数
complex(real [,imag ])  创建一个复数
str(x )             将对象 x 转换为字符串
repr(x )            将对象 x 转换为表达式字符串
tuple(s )           将序列 s 转换为一个元组
list(s )            将序列 s 转换为一个列表
chr(x )             将一个整数转换为一个字符
unichr(x )          将一个整数转换为Unicode字符
ord(x )             将一个字符转换为它的整数值
hex(x )             将一个整数转换为一个十六进制字符串
oct(x )             将一个整数转换为一个八进制字符串


4、流程控制语句

 和C语言大同小异,逻辑判断用的是
and, or, not
, 比较大小可以类似这样写
7 < a < 10


5、字符串相关:下标,切片

string = "abcdef"
print(string[0])
print(string[1])
print(string[3])


输出结果:

a
b
d


切片语法: [起始位置:结束位置:步长],是左开右闭

string = "abcdefgh"
print(string[0:2])
print(string[2:7:2])
print(string[2:])
print(string[1:-1])
print(string[::2])
print(string[::-2])
print(string[5:1:-2])
print(string[::-1])


输出结果:

ab
ceg
cdefgh
bcdefg
aceg
hfdb
fd
hgfedcba


5、列表、元组、字典

#列表操作:
增 list.append(obj), list.extend(collection), list.insert(index, obj)
删 del list[index], list.pop(), list.remove(value)
改 根据下标改
查 循环迭代
找 in,not in关键字

#元组操作:
元组只能查,不能改

#字典操作:
增和改 dict['key'] = value key存在就是改,key不存在就是增, dict.update(dict2)
删 del dict['key'], del dict, dict.clear()
查 keys = dict.keys(), values = dict.values(), items = dict.items() 循环迭代
找 dict.has_key(key), in关键字

#集合操作:集合不允许有元素重复,元素之间没有顺序
增 set.add(value)
删 set.remove(value), del set
改 set.update(newset)
查 循环迭代,没有顺序
找 in关键字
交 set1 & set2
并 set1 | set2
差 set1 - set2
异或 set1 ^ set2


6、函数

函数的缺省参数必须放到参数列表的最后面

可变参数:*args存元组,**kwargs是字典

Python中函数参数是引用传递(注意不是值传递)。对于不可变类型,因变量不能修改,所以运算不会影响到变量自身;而对于可变类型来说,函数体中的运算有可能会更改传入的参数变量。

匿名函数: lambda [arg1 [,arg2,…..argn]]:expression

Lambda函数能接收任何数量的参数但只能返回一个表达式的值

stus = [
{"name":"zhangsan", "age":18},
{"name":"lisi", "age":19},
{"name":"wangwu", "age":17}
]
stus.sort(key = lambda x:x['name']) #按name排序
stus.sort(key = lambda x:x['age']) #按age排序


7、文件操作

PS:文件打开方式有r(read),w(write),a(append),b(binary),+(读写)。写访问文件时,如果不存在会创建一个新文件,读则不会。

#读取一个文件  open(文件名,访问模式)
file = open("text.txt",'w')
#关闭文件
file.close()
#读文件
读所有     file.read()
读字节     file.read(bytes)
所有行     file.readlines()
读一行     file.readline()
#写文件
content = "hello world"
file.write(content)


8、面向对象

详见这里写链接内容

9、异常、模块、包

捕获异常:
try...except...finally...


抛出异常:
raise ...Exception


导入模块:
import module #那么调用函数的时候用module.函数名()


从模块导入函数:
from 模块 import 函数名 #那么可以直接调用函数


如果一个文件中有
__all__
变量,那么也就意味着这个变量中的元素,不会被
from xxx import *
时导入

引入包中的模块:
import 文件.模块
或者
from 文件夹 import 模块,如果该文件为空,那么仅仅导入这个包,不导入模块


包中的
__init__.py 控制着包的导入行为,在__init__.py文件中,定义一个__all__变量,它控制着 from 包名 import *时导入的模块


10、元类和动态添加属性和方法

(类也是个对象,可以添加属性,方法等。这类似于js中的原型链)

>>> class ObjectCreator(object):
…       pass

>>> print ObjectCreator     # 你可以打印一个类,因为它其实也是一个对象
<class '__main__.ObjectCreator'>
>>> def echo(o):
…       print o
…
>>> echo(ObjectCreator)                 # 你可以将类做为参数传给函数
<class '__main__.ObjectCreator'>
>>> print hasattr(ObjectCreator, 'new_attribute')
Fasle
>>> ObjectCreator.new_attribute = 'foo' #  你可以为类增加属性
>>> print hasattr(ObjectCreator, 'new_attribute')
True
>>> print ObjectCreator.new_attribute
foo
>>> ObjectCreatorMirror = ObjectCreator # 你可以将类赋值给一个变量
>>> print ObjectCreatorMirror()
<__main__.ObjectCreator object at 0x8997b4c>

>>> def choose_class(name):
…       if name == 'foo':
…           class Foo(object):
…               pass
…           return Foo     # 返回的是类,不是类的实例
…       else:
…           class Bar(object):
…               pass
…           return Bar
…
>>> MyClass = choose_class('foo')
>>> print MyClass              # 函数返回的是类,不是类的实例
<class '__main__'.Foo>
>>> print MyClass()            # 你可以通过这个类创建类实例,也就是对象
<__main__.Foo object at 0x89c6d4c>

>>> print type(1) #数值的类型
<type 'int'>
>>> print type("1") #字符串的类型
<type 'str'>
>>> print type(ObjectCreator()) #实例对象的类型
<class '__main__.ObjectCreator'>
>>> print type(ObjectCreator) #类的类型
<type 'type'>

#===============================================================
#用type创建类
#type(类名, 由父类名称组成的元组(针对继承的情况,可以为空),包含属性的字典(名称和值))
Test2 = type("Test2",(),{}) #定了一个Test2类
In [5]: Test2() #创建了一个Test2类的实例对象
Out[5]: <__main__.Test2 at 0x10d406b38>

Foo = type('Foo', (), {'bar':True})
>>> print Foo
<class '__main__.Foo'>
>>> print Foo.bar
True
>>> f = Foo()
>>> print f
<__main__.Foo object at 0x8a9b84c>
>>> print f.bar
True

>>> FooChild = type('FooChild', (Foo,),{})
>>> print FooChild
<class '__main__.FooChild'>
>>> print FooChild.bar   # bar属性是由Foo继承而来
True

#===============================================================
#用type添加方法
In [46]: def echo_bar(self): #定义了一个普通的函数
...:     print(self.bar)
...:

In [47]: FooChild = type('FooChild', (Foo,), {'echo_bar': echo_bar}) #让FooChild类中的echo_bar属性,指向了上面定义的函数

In [48]: hasattr(Foo, 'echo_bar') #判断Foo类中,是否有echo_bar这个属性
Out[48]: False

In [49]:

In [49]: hasattr(FooChild, 'echo_bar') #判断FooChild类中,是否有echo_bar这个属性
Out[49]: True

In [50]: my_foo = FooChild()

In [51]: my_foo.echo_bar()
True
#===============================================================
#添加静态方法
In [36]: @staticmethod
...: def testStatic():
...:     print("static method ....")
...:

In [37]: Foochild = type('Foochild', (Foo,), {"echo_bar":echo_bar, "testStatic":
...: testStatic})

In [38]: fooclid = Foochild()

In [39]: fooclid.testStatic
Out[39]: <function __main__.testStatic>

In [40]: fooclid.testStatic()
static method ....

In [41]: fooclid.echo_bar()
True

#===============================================================
#添加类方法
In [42]: @classmethod
...: def testClass(cls):
...:     print(cls.bar)
...:

In [43]:

In [43]: Foochild = type('Foochild', (Foo,), {"echo_bar":echo_bar, "testStatic":
...: testStatic, "testClass":testClass})

In [44]:

In [44]: fooclid = Foochild()

In [45]: fooclid.testClass()
True


#__class__属性
>>> age = 35
>>> age.__class__
<type 'int'>
>>> name = 'bob'
>>> name.__class__
<type 'str'>
>>> def foo(): pass
>>>foo.__class__
<type 'function'>
>>> class Bar(object): pass
>>> b = Bar()
>>> b.__class__
<class '__main__.Bar'>

>>> a.__class__.__class__
<type 'type'>
>>> age.__class__.__class__
<type 'type'>
>>> foo.__class__.__class__
<type 'type'>
>>> b.__class__.__class__
<type 'type'>


python创建类的过程:

1.Foo中有__metaclass__这个属性吗?如果是,Python会通过__metaclass__创建一个名字为Foo的类(对象)
2.如果Python没有找到__metaclass__,它会继续在Bar(父类)中寻找__metaclass__属性,并尝试做和前面同样的操作。
3.如果Python在任何父类中都找不到__metaclass__,它就会在模块层次中去寻找__metaclass__,并尝试做同样的操作。
4.如果还是找不到__metaclass__,Python就会用内置的type来创建这个类对象。


动态添加方法

import types

#定义了一个类
class Person(object):
num = 0
def __init__(self, name = None, age = None):
self.name = name
self.age = age
def eat(self):
print("eat food")

#定义一个实例方法
def run(self, speed):
print("%s在移动, 速度是 %d km/h"%(self.name, speed))

#定义一个类方法
@classmethod
def testClass(cls):
cls.num = 100

#定义一个静态方法
@staticmethod
def testStatic():
print("---static method----")

#创建一个实例对象
P = Person("老王", 24)
#调用在class中的方法
P.eat()

#给这个对象添加实例方法
P.run = types.MethodType(run, P)
#调用实例方法
P.run(180)

#给Person类绑定类方法
Person.testClass = testClass
#调用类方法
print(Person.num)
Person.testClass()
print(Person.num)

#给Person类绑定静态方法
Person.testStatic = testStatic
#调用静态方法
Person.testStatic()


如果我们想要限制实例的属性怎么办?比如,只允许对Person实例添加name和age属性。

为了达到限制的目的,Python允许在定义class的时候,定义一个特殊的slots变量,来限制该class实例能添加的属性:

>>> class Person(object):
__slots__ = ("name", "age")

>>> P = Person()
>>> P.name = "老王"
>>> P.age = 20
>>> P.score = 100
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
AttributeError: Person instance has no attribute 'score'
>>>
#__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: