1. 程式人生 > >Python學習筆記(2)位元操作、類、檔案操作

Python學習筆記(2)位元操作、類、檔案操作

位元操作
注意一: 適用範圍 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