chapter01-1-python需要知道的基础

2018-03-17  本文已影响0人  Yin小贱

仅学习用,引用自《零基础学Python》张志强、赵越等编著

文件类型

编码规范

class Person:   #类名
    __name = ""   #私有变量
    def __init__(self,name):         
        self.__name=name  #self相当于java中的this,指当前类
    def getName(self):  #方法名首字母小写,其后每个单词首字母大写
        return self.__name

if __name__=="__main__":
    person=Person("jack")  #对象名小写
    print(person.getName())
if x==1:
  print 'x>0'
if x==-1:
  print 'x<0'
import sys
print (sys.path)
print (sys.argv)
  1. from...import...语句
    与import语句不同,from...import...语句只导入模块中的一部分内容,并在当前的命名空间创建导入对象的引用;而import语句在当前程序的命名空间中创建导入模块的引用,从而可以使用"sys.path"的方式调用sys模块中的内容
from sys import path
from sys import argv

print (path)
print (argv)
# this is comment
# this is annother comment
########################

name="javck"
print (name)
# -*- coding: UTF-8 -*-
print ("hello python")
print ("hello python");

变量和常量

#正确的变量命名
var=1
_var=1
var_=1
var1=1
#错误的变量命名
1var=1
$var=1
#一次新的赋值操作,将创建一个新的变量
#以下两次打印的同一个变量的id不一样
x = 1
print (id(x))
x = 2
print (id(x))
print (y)   #如果没有赋值,则python认为不存在,未定义
def fun():
  local =1   #局部变量local
  print (local)
fun()
#在文件开头定义全局变量
a=1
b=2
def add():
  global a #global关键字引用全局变量
  a = 3
  return "a + b",a+b
def sub():
  global b
  b=4
  return "a - b" ,a-b

print (add())
print (sub())
#const.py
class _const:    #定义常量类const
    class ConstError(TypeError): pass  #继承处TypeError
    def __setattr__(self,name,value):
        if self.__dict__.has_key(name):  #如果__dict__中不包含对应的key则抛出错误
            raise self.ConstError, "Can't rebind const(%s)"%name
        self.__dict__[name]=value

import sys
sys.modules[__name__]=_const()   #将const注册进sys.modules的全局dict中
import const
Person.magic=23
Person.magic=33   #抛出异常const.ConstError: Can't rebind const(magic)
a =1
b= 0.1
c= 2+3j
print(type(c))
str = 'hello world'
str2 = "hello world"
str3 = '''hello world'''
str3 = ''' "hello world ,I'm Chinese" '''

运算符与表达式

运算符 描述
+ 加法
- 减法
* 乘法
/ 除法
% 求模
** 求幂
运算符 描述
> 大于
< 小于
>= 大于等于
<= 小于等于
== 等于
!= 不等于
运算符 描述 表达式
and 逻辑与 x and y 当x为True时才计算y
or 逻辑或 x and y 当x为False时才计算y
not 逻辑非 not x
上一篇 下一篇

猜你喜欢

热点阅读