下面的笔记内容依然来自于codecademy
比特操作 注意一: 适用范围 Note that you can only do bitwise operations on an integer. Trying to do them on strings or floats will result in nonsensical output!
print 5 >> 4 # Right Shift
print 5 << 1 # Left Shift
print 8 & 5 # Bitwise AND
print 9 | 4 # Bitwise OR
print 12 ^ 42 # Bitwise XOR
print ~88 # Bitwise NOT
比特操作 - 打印二进制
print 0b1, #1
print 0b10, #2
print 0b11, #3
print 0b100, #4
print 0b101, #5
print 0b110, #6
print 0b111 #7
print "******"
print 0b1 + 0b11
print 0b11 * 0b11
比特操作 - 将十进制的number转换为二进制的str 注意(1) 可以将十进制转换为二进制bin()、八进制oct()、十六进制hex(),转换后为str型,不再是number
print bin(1)
for i in range(2,6):
print bin(i)
比特操作 - 将二进制的str转换为十进制的number
print int("1",2)
print int("10",2)
print int("111",2)
print int("0b100",2)
print int(bin(5),2)
# Print out the decimal equivalent of the binary 11001001.
print int("11001001",2)
比特操作-左移右移(slide to the left, slide to the right) 1 Note that using the & operator can only result in a number that is less than or equal to the smaller of the two values
2 Note that the bitwise | operator can only create results that are greater than or equal to the larger of the two integer inputs.
shift_right = 0b1100
shift_left = 0b1
# Your code here!
shift_right=shift_right >>2
shift_left=shift_left<<2
print bin(shift_right)
print bin(shift_left)
比特操作-NOT 1 Just know that mathematically, this is equivalent to adding one to the number and then making it negative.
2 just flips all of the bits in a single number
print ~1
print ~2
print ~3
print ~42
print ~123
比特操作-Mask-例1
A bit mask is just a variable that aids you with bitwise operations. A bit mask can help you turn specific bits on, turn others off, or just collect data from an integer about which bits are on or off
判断右起第4位是否是1,即,判断右起第4位的开关是否已经打开
def check_bit4(input):
input1=int(bin(input),2)
input2=0b1000
if(input1&input2):
return "on"
else:
return "off"
比特操作-Mask-例2
确保第3为是1
a = 0b10111011
mask=0b100
desired=a|mask
print bin(desired)
比特操作 - XOR - 使用异或 - to flip every bit XOR符号是^
a = 0b11101110
mask=0b11111111
desired=a ^ mask
print bin(desired)
比特操作 - XOR - 使用异或 - to flip 某一位 bit
def flip_bit(number,n):
mask=0b1<<(n-1)
result=mask^number
return bin(result)
Python中的类 - 类的定义 1 A class is just a way of organizing and producingobjects with similarattributes andmethods. 2 You can think of an object as a single data structure that contains data as well as functions; functions of objects are calledmethods. Python中的类 - 例1
class Fruit(object):
"""A class that makes various tasty fruits."""
def __init__(self, name, color, flavor, poisonous):
self.name = name
self.color = color
self.flavor = flavor
self.poisonous = poisonous
def description(self):
print "I'm a %s %s and I taste %s." % (self.color, self.name, self.flavor)
def is_edible(self):
if not self.poisonous:
print "Yep! I'm edible."
else:
print "Don't eat me! I am super poisonous."
lemon = Fruit("lemon", "yellow", "sour", False)
lemon.description()
lemon.is_edible()
如上, 注意一,类定义中的(object); 官方解释是:We also use the word object in parentheses because we want our classes to inherit the object class. This means that our class has all the properties of an object, which is the simplest, most basic class. 也就是说,object是最最基础的类,默认会写在class的参数中。 注意二,对_ _inti_ _( )的理解应该是怎样的?There is a special function named __init__() that gets called whenever we create a new instance of a class. It exists by default, even though we don't see it. However, we can define our own __init__() function inside the class, overwriting the default version. 注意三,在_ _init_ _( )的赋值方式 注意四,在_ _init_ _( )的参数的写法。The first argument passed to __init__() must always be the keyword self - this is how the object keeps track of itself internally - but we can pass additional variables after that. 扩大推广,any class method must have self as their first parameter. Python中的类 - 例2
class Animal(object): #object是python中的类,Animal是用户自定义的类,用户自定义的类首字母大写
def __init__(self,name): #self表示当前的对象,类似C++中的class的*this, 一般放在参数中的第一位。
self.name=name
zebra= Animal("Jeffrey")
print zebra.name
如上,可以看出,貌似Python中没有private, protected,public这样的关键字。并且,在_ _init _ _( )函数中,不仅完成了构造函数,而且完成了对成员变量的声明。 Class Scope When dealing with classes, you can have 1) variables that are available everywhere (global variables), 2) variables that are only available to members of a certain class (member variables), and 3) variables that are only available to particular instances of a class (instance variables). You can also have functions 1) some functions are available everywhere, 2) some functions are only available to members of a certain class, 3) some functions are only available to particular instance objects.
注意1 line3 is_alive和line 4 health是member variable。 member variable的含义是 : Each class object we create has itsown set of member variables. 注意2 在函数中的self. variable(line 5)其实也是一种member variable。In order to assign a variable to the class (creating a member variable), we use dot notation. In order to access the member variables, we also use dot notation, whether it is created within the class or values are passed into the new object at initialization. 注意3 所以在line 21修改了member variable ocelot.health的值后,并没有影响到另外两个类的实例中,health的取值.
class ShoppingCart(object):
"""Creates shopping cart objects
for users of our fine website."""
items_in_cart = {}
def __init__(self, customer_name):
self.customer_name = customer_name
def add_item(self, product, price):
"""Add product to the cart."""
if not product in self.items_in_cart:
self.items_in_cart[product] = price
print product + " added."
else:
print product + " is already in the cart."
def remove_item(self, product):
"""Remove product from the cart."""
if product in self.items_in_cart:
del self.items_in_cart[product]
print product + " removed."
else:
print product + " is not in the cart."
my_cart=ShoppingCart("Goerge")
my_cart.add_item("lemon",3.14)
如上,是一个更贴近生活的例子, ShoppintCart Inheritance and Override
class Employee(object):
"""Models real-life employees!"""
def __init__(self, employee_name):
self.employee_name = employee_name
def calculate_wage(self, hours):
self.hours = hours
return hours * 20.00
# Add your code below!
class PartTimeEmployee(Employee): #inheritance
def calculate_wage(self, hours): #override
self.hours=hours #because of override, this line have to be here again
return hours*12.00
注意一 为什么要把object作为参数? Normally we use object as the parent class because it is the most basic type of class, but by specifying a different class, we can inherit more complicated functionality. Super 关键字的使用
class Employee(object):
"""Models real-life employees!"""
def __init__(self, employee_name):
self.employee_name = employee_name
def calculate_wage(self, hours):
self.hours = hours
return hours * 20.00
# Add your code below!
class PartTimeEmployee(Employee): #inheritance
def calculate_wage(self, hours): #override
self.hours=hours #because of override, this line have to be here again
return hours*12.00
def full_time_wage(self, hours):
return super(PartTimeEmployee,self).calculate_wage(hours)
milton = PartTimeEmployee("Milton")
print milton.full_time_wage(10)
重载内建函数 __repr__( )控制类的表现
class Point3D(object):
def __init__(self,x,y,z):
self.x=x
self.y=y
self.z=z
def __repr__(self):
return "(%d, %d, %d)" % (self.x, self.y, self.z)
my_point = Point3D(1,2,3)
print my_point
we can override the built-in __repr__() method, which is short for representation; by providing a return value in this method, we can tell Python how to represent an object of our class (for instance, when using a print statement).
Python的I/O控制-读写文件操作1
my_list = [i**2 for i in range(1,11)]
# Generates a list of squares of the numbers 1 - 10
f = open("output.txt", "w")
for item in my_list:
f.write(str(item) + "\n")
f.close()
Python的I/O控制-读写文件操作2
my_file=open("output.txt","r+")
You can open files in write-only mode ("w"), read-only mode ("r"), read and write mode ("r+"), and append mode ("a", which adds any new data you write to the file to the end of the file). Python的I/O控制-读写文件操作3
my_file =open("output.txt","r")
print my_file.read()
my_file.close()
Python的I/O控制-读写文件操作4
my_file=open("text.txt", "r")
print my_file.readline() #readline()每次读一行
print my_file.readline()
print my_file.readline()
my_file.close()
Python的I/O控制-读写文件都要记住要close()的原因是什么? We keep telling you that you always need to close your files after you're done writing to them. Here's why! During the I/O process, data is buffered: this means that it is held in a temporary location before being written to the file. Python doesn't flush the buffer—that is, write data to the file—until it's sure you're done writing. One way to do this is to close the file. If you write to a file without closing, the data won't make it to the target file.
读写文件操作5 自动关闭文件
You may not know this, but file objects contain a special pair of built-in methods: __enter__() and __exit__(). The details aren't important, but what is important is that when a file object's __exit__() method is invoked, it automatically closes the file. How do we invoke this method? With with and as.
with open("text.txt", "w") as textfile:
textfile.write("Success!")
读写文件操作6 如何判断文件是否已经关闭
with open("text.txt","w") as my_file:
my_file.write("hello python")
if my_file.closed==False:
my_file.close()
print my_file.closed