返回顶部
首页 > 资讯 > 后端开发 > Python >Python学习笔记(2)比特操作、类、
  • 110
分享到

Python学习笔记(2)比特操作、类、

学习笔记操作Python 2023-01-31 06:01:34 110人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

下面的笔记内容依然来自于codecademy 比特操作注意一: 适用范围 Note that you can only do bitwise operations on an integer. Trying to do them on s

下面的笔记内容依然来自于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


--结束END--

本文标题: Python学习笔记(2)比特操作、类、

本文链接: https://lsjlt.com/news/189428.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

猜你喜欢
  • Python学习笔记(2)比特操作、类、
    下面的笔记内容依然来自于codecademy 比特操作注意一: 适用范围 Note that you can only do bitwise operations on an integer. Trying to do them on s...
    99+
    2023-01-31
    学习笔记 操作 Python
  • Python学习笔记(2)操作符和数据类
    2019-02-25 一: (1)常用操作符:   ① 算数操作符:=、-、*、/、%(求余)、**(幂运算)、//(地板除法:计算结果取比商小的最大整型)   注意:幂运算操作符比其左侧的一元运算符的优先级高,比其右边的一元运算符优先级...
    99+
    2023-01-30
    学习笔记 操作 数据
  • Python学习笔记(2)
    Python开发IDE:pycharm   ,eclipse 快捷键:Ctrl+?整体注释 一·运算符   +(加)   -(减)  *(乘)   /(除)  **(幂)  %(余)   //(商)     判断某个东西是否在某个东西里边...
    99+
    2023-01-30
    学习笔记 Python
  • Python学习笔记(2)
    Unicode字符串: GB2312编码为表示中文产生 python内部编码是unicode编码Unicode通常用两个字节表示一个字符,原有的英文编码从单字节变成双字节,只需要把高字节全部填0 就可以以Unicode表示的字...
    99+
    2023-01-31
    学习笔记 Python
  • Python 学习笔记 - 操作MySQ
    Python里面操作MySQL可以通过两个方式:pymysql模块ORM框架的SQLAchemey本节先学习第一种方式。学习Python模块之前,首先看看MySQL的基本安装和使用,具体语法可以参考豆子之前的博客http://beanxyz...
    99+
    2023-01-31
    学习笔记 操作 Python
  • Python学习笔记2——Python概
    Python概述   语言:交流的工具,沟通媒介   计算机语言:人跟计算机交流的工具,翻译官   Python是计算机语言里的一种     代码:人类语言,同过代码命令机器,跟机器交流     Python解释器: 就是那个担任翻译工作...
    99+
    2023-01-30
    学习笔记 Python
  • [Python学习笔记] 数字类型及操作
    数字类型 整数类型 十进制:1110,-123 二进制:以0B或0b开头 0b110,-0B101 八进制:以0O或0o开头 0o123,-0O567 十六进制:以0X或0x开头 0x555,-0X89a 浮点数类型...
    99+
    2023-01-31
    学习笔记 类型 操作
  • python学习笔记2—python文件
    python学习笔记2——python文件类型、变量、数值、字符串、元组、列表、字典一、Python文件类型1、源代码python源代码文件以.py为扩展名,由pyton程序解释,不需要编译[root@localhost day01]# v...
    99+
    2023-01-31
    学习笔记 文件 python
  • python学习笔记(十)、文件操作
    在前面我们了解到了没得模块,其中有一个模块为fileinput,为文件操作模块,不知道小伙伴们是否还记得?   1 打开文件   要打开文件,可以使用fileinput中的fileinput.input函数进行打开,也可以使用模块 io ...
    99+
    2023-01-31
    学习笔记 操作 文件
  • python学习笔记(一)-文件操作
    python的基本文件操作是包含在__buildin__模块中的。   I, 基本操作1, 打开fh=open('filename', 'r')   fh是打开文件的handle,每一个被打开的文件都应该退出时关闭(除了handle没有赋给...
    99+
    2023-01-31
    学习笔记 操作 文件
  • Python第五周 学习笔记(2)
    一、实现一个cache装饰器,实现可过期被清除的功能 简化设计,函数的形参定义不包含可变位置参数、可变关键词参数和keyword-only参数 可以不考虑缓存满了之后的换出问题 1)原始 def cache(fn): imp...
    99+
    2023-01-31
    学习笔记 Python
  • 【gcc】RtpTransportControllerSend学习笔记 2
    在【gcc】RtpTransportControllerSend学习笔记 1 中, 跟着 大神ishen 从RtpTransportControllerSend 到cc-controller对gc...
    99+
    2023-10-07
    学习 笔记
  • JAVA学习笔记- - - day 2
     💕前言:作者是一名正在学习JAVA的初学者,每天分享自己的学习笔记,希望能和大家一起进步成长💕 目录  💕前言:作者是一名正在学习JAVA的初学者,每天分享自己的学习笔记,希望能和...
    99+
    2023-09-04
    学习
  • python3学习笔记(2)----p
    1、python3的基本数据类型 Python 中的变量不需要声明。每个变量在使用前都必须赋值,变量赋值以后该变量才会被创建。在 Python 中,变量就是变量,它没有类型,我们所说的"类型"是变量所指的内存中对象的类型。等号(=)用来给...
    99+
    2023-01-31
    学习笔记
  • Python学习笔记:第2天while循
    目录 1. while循环 continue、break和else语句 2. 格式化输出 3. 运算符 ...
    99+
    2023-01-30
    学习笔记 Python
  • Linux学习笔记 Day 2~3
    继续整理周末课程的Linux学习笔记。 vim编辑器 最受欢迎的是emacs,vim是vi的增强版本,特点是编辑内容时有颜色变化。命令:vim /etc/passwd 三种模式: 1. 普通模式-->可视模式 2....
    99+
    2023-01-31
    学习笔记 Linux Day
  • Python数据类型学习笔记
    带你走进数据类型 一:整数、浮点数 Python中整数和浮点数的定义以及运算和C++都是一样的,我在这里就不需多说了,我就说明一点:Python相对于C/C++而言,定义整数没有int 和 long lon...
    99+
    2022-06-04
    数据类型 学习笔记 Python
  • Python学习日记-2
    *使用pickle处理数据存储,类似于java中的serialization,是将对象转化为二进制码存入文件中,主要函数pickle.dump(obj,file),pickle.load(file) *在每个文件加入后缀.pkl,实现逐行数...
    99+
    2023-01-31
    日记 Python
  • MySql学习笔记(五):explain-数据读取操作的操作类型
    explain命令如下:mysql> explain select * from t_blog; +----+-------------+-...
    99+
    2024-04-02
  • mysql学习笔记(2-初始化)
    初始化:(1)给root用户设置密码(三种方式): SET PASSWORD FOR 'username'@'host' = PASSWORD('your_password'); updat...
    99+
    2024-04-02
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作