Fundamentals 29 min read

Master Python Essentials: Numbers, Strings, Functions, and Objects Explained

This comprehensive guide walks through Python fundamentals, covering numeric operations, base conversions, ASCII handling, logical checks, type casting, string manipulation, slicing, lambda usage, data structures, class definitions, object introspection, and useful built‑in functions, complete with clear code examples and explanations.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master Python Essentials: Numbers, Strings, Functions, and Objects Explained

一、 数字

1 求绝对值

绝对值或复数的模

# 公众号:快学Python
In [1]: abs(-6)
Out[1]: 6

2 进制转化

十进制转换为二进制:

In [2]: bin(10)
Out[2]: '0b1010'

十进制转换为八进制:

In [3]: oct(9)
Out[3]: '0o11'

十进制转换为十六进制:

In [4]: hex(15)
Out[4]: '0xf'

3 整数和ASCII互转

十进制整数对应的

ASCII字符
In [1]: chr(65)
Out[1]: 'A'

查看某个 ASCII字符 对应的十进制数

In [1]: ord('A')
Out[1]: 65

4 元素都为真检查

所有元素都为真,返回 True ,否则为

False
In [5]: all([1,0,3,6])
Out[5]: False
In [6]: all([1,2,3])
Out[6]: True

5 元素至少一个为真检查

至少有一个元素为真返回 True ,否则

False
In [7]: any([0,0,0,[]])
Out[7]: False
In [8]: any([0,0,1])
Out[8]: True

6 判断是真是假

测试一个对象是True, 还是False.

In [9]: bool([0,0,0])
Out[9]: True
In [10]: bool([])
Out[10]: False
In [11]: bool([1,0,1])
Out[11]: True

7 创建复数

创建一个复数

In [1]: complex(1,2)
Out[1]: (1+2j)

8 取商和余数

分别取商和余数

In [1]: divmod(10,3)
Out[1]: (3, 1)

9 转为浮点类型

将一个整数或数值型字符串转换为浮点数

In [1]: float(3)
Out[1]: 3.0

如果不能转化为浮点数,则会报 ValueError:

In [2]: float('a')
# ValueError: could not convert string to float: 'a'

10 转为整型

int(x, base=10)

,x可能为字符串或数值,将x转换为普通整数。

In [1]: int('12',16)
Out[1]: 18

11 次幂

base为底的exp次幂,如果mod给出,取余

In [1]: pow(3, 2, 4)
Out[1]: 1

12 四舍五入

四舍五入, ndigits 代表小数点后保留几位:

In [11]: round(10.0222222, 3)
Out[11]: 10.022
In [12]: round(10.05,1)
Out[12]: 10.1

13 链式比较

i = 3
print(1 < i < 3)  # False
print(1 < i <= 3)  # True

二、 字符串

14 字符串转字节

字符串转换为字节类型

s = "apple"
bytes(s,encoding='utf-8')
Out: b'apple'

15 任意对象转为字符串

i = 100
str(i)  # '100'
str([])  # '[]'
str(tuple())  # '()'

16 执行字符串表示的代码

将字符串编译成Python能识别或可执行的代码。

s = "print('helloworld')"
r = compile(s,"<string>","exec")
exec(r)  # helloworld

17 计算表达式

将字符串当成有效的表达式来求值并返回计算结果。

s = "1 + 3 +5"
eval(s)  # 9

18 字符串格式化

格式化输出字符串, format(value, format_spec) 实质上是调用了 value.__format__(format_spec) 方法。

print("i am {0},age{1}".format("tom",18))  # i am tom,age18

三、 函数

19 拿来就用的排序函数

排序:

a = [1,4,2,3,1]
sorted(a,reverse=True)  # [4, 3, 2, 1, 1]
a = [{'name':'xiaoming','age':18,'gender':'male'},{'name':'xiaohong','age':20,'gender':'female'}]
sorted(a,key=lambda x: x['age'],reverse=False)
# [{'name':'xiaoming','age':18,'gender':'male'},{'name':'xiaohong','age':20,'gender':'female'}]

20 求和函数

求和:

a = [1,4,2,3,1]
sum(a)  # 11
sum(a,10)  # 21 (initial value 10)

21 nonlocal用于内嵌函数中

关键词 nonlocal 常用于函数嵌套中,声明变量 i 为非局部变量。

def excepter(f):
    i = 0
    def wrapper():
        try:
            f()
        except Exception as e:
            nonlocal i
            i += 1
            print(f'{e.args[0]}: {i}')
    return wrapper

22 global 声明全局变量

使用 global 让函数内部修改全局变量。

i = 0

def h():
    global i
    i += 1

h()
print(i)  # 1

23 交换两元素

def swap(a, b):
    return b, a
print(swap(1, 0))  # (0, 1)

24 操作函数对象

def f():
    print('i')

def g():
    print('i')

[f,g][1]()  # i

25 生成逆序序列

list(range(10,-1,-1))  # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

26 函数的五类参数使用例子

Python 五类参数:位置参数,关键字参数,默认参数,可变位置或关键字参数。

def f(a,*b,c=10,**d):
    print(f'a:{a},b:{b},c:{c},d:{d}')

f(1,2,5,width=10,height=20)
# a:1,b:(2, 5),c:10,d:{'width': 10, 'height': 20}

f(a=1,c=12)
# a:1,b:(),c:12,d:{}

27 使用slice对象

定义 slice 对象以复用切片操作。

perfect_cake_slice_way = slice(1,10,2)
cake1_slice = cake1[perfect_cake_slice_way]
cake2_slice = cake2[perfect_cake_slice_way]

28 lambda 函数的动画演示

示例说明 lambda 的返回值。

def max_len(*lists):
    return max(*lists, key=lambda v: len(v))

r = max_len([1,2,3],[4,5,6,7],[8])
print(f'更长的列表是{r}')
# 更长的列表是[4,5,6,7]

四、 数据结构

29 转为字典

dict()
dict(a='a',b='b')
dict(zip(['a','b'],[1,2]))
dict([('a',1),('b',2)])

30 冻结集合

frozenset([1,1,3,2,3])  # frozenset({1, 2, 3})

31 转为集合类型

a = [1,4,2,3,1]
set(a)  # {1, 2, 3, 4}

32 转为切片对象

class slice(start, stop[, step]) 返回表示索引集的切片对象。

a = [1,4,2,3,1]
my_slice_meaning = slice(0,5,2)
a[my_slice_meaning]  # [1, 2, 1]

33 转元组

i_am_list = [1,3,5]
i_am_tuple = tuple(i_am_list)
# (1, 3, 5)

五、 类和对象

34 是否可调用

callable(str)  # True
callable(int)  # True
class Student():
    def __init__(self,id,name):
        self.id = id
        self.name = name
    def __repr__(self):
        return f'id = {self.id}, name = {self.name}'

xiaoming = Student('001','xiaoming')
callable(xiaoming)  # False

实现 __call__ 后实例即可被调用。

class Student():
    def __call__(self):
        print('I can be called')
        print(f'my name is {self.name}')

t = Student('001','xiaoming')
t()
# I can be called
# my name is xiaoming

35 ascii 展示对象

class Student():
    def __repr__(self):
        return f'id = {self.id}, name = {self.name}'

xiaoming = Student('1','xiaoming')
print(xiaoming)
# id = 1, name = xiaoming
print(ascii(xiaoming))
# 'id = 1, name = xiaoming'

36 类方法

使用 @classmethod 定义不需要实例化的类方法。

class Student():
    @classmethod
    def f(cls):
        print(cls)

37 动态删除属性

delattr(xiaoming,'id')
hasattr(xiaoming,'id')  # False

38 一键查看对象所有方法

dir(xiaoming)
# ['__class__', '__delattr__', '__dict__', ... 'name']

39 动态获取对象属性

getattr(xiaoming,'name')  # 'xiaoming'

40 对象是否有这个属性

hasattr(xiaoming,'name')  # True
hasattr(xiaoming,'address')  # False

41 对象门牌号

id(xiaoming)  # e.g., 98234208

42 isinstance

isinstance(xiaoming,Student)  # True

43 父子关系鉴定

class undergraduate(Student):
    pass
issubclass(undergraduate,Student)  # True
issubclass(object,Student)  # False
issubclass(Student,object)  # True

44 所有对象之根

o = object()
type(o)  # object

45 创建属性的两种方式

使用 property 类或装饰器实现属性 getter、setter、deleter。

class C:
    def __init__(self):
        self._x = None
    def getx(self):
        return self._x
    def setx(self,value):
        self._x = value
    def delx(self):
        del self._x
    x = property(getx,setx,delx,"I'm the 'x' property.")

class C:
    @property
    def x(self):
        return self._x
    @x.setter
    def x(self,value):
        self._x = value
    @x.deleter
    def x(self):
        del self._x

46 查看对象类型

type(xiaoming)  # __main__.Student
type(tuple())  # tuple

47 元类

类本身是对象, type 是所有类的元类。

Student = type('Student',(),{})
print(Student)  # __main__.Student
StudentMirror = Student
Student.class_property = 'class_property'
hasattr(Student,'class_property')  # True

六、 工具

48 枚举对象

s = ["a","b","c"]
for i,v in enumerate(s,1):
    print(i,v)
# 1 a
# 2 b
# 3 c

49 查看变量所占字节数

import sys
a = {'a':1,'b':2.0}
sys.getsizeof(a)  # 240

50 过滤器

fil = filter(lambda x: x>10,[1,11,2,45,7,6,13])
list(fil)  # [11, 45, 13]

51 返回对象的哈希值

hash(xiaoming)  # e.g., 6139638
# hash([1,2,3]) raises TypeError

52 一键帮助

help(xiaoming)
# Displays class documentation and methods

53 获取用户输入

input()  # e.g., user types 'aa' → returns 'aa'

54 创建迭代器类型

lst = [1,3,5]
for i in iter(lst):
    print(i)
# 1 3 5

55 打开文件

fo = open('D:/a.txt',mode='r',encoding='utf-8')
fo.read()
# '\ufefflife is not so long,
I use Python to play.'

Mode取值表:

56 创建range序列

range(11)  # range(0, 11)
range(0,11,1)  # range(0, 11)

57 反向迭代器

rev = reversed([1,4,2,3,1])
for i in rev:
    print(i)
# 1 3 2 4 1

58 聚合迭代器

x = [3,2,1]
y = [4,5,6]
list(zip(y,x))  # [(4, 3), (5, 2), (6, 1)]

a = range(5)
b = list('abcde')
[str(y)+str(x) for x,y in zip(a,b)]  # ['a0','b1','c2','d3','e4']

59 链式操作

from operator import (add, sub)

def add_or_sub(a, b, oper):
    return (add if oper=='+' else sub)(a, b)

add_or_sub(1, 2, '-')  # -1

60 对象序列化

使用 json.dump 将对象列表序列化为 JSON 文件。

class Student():
    def __init__(self,**args):
        self.ids = args['ids']
        self.name = args['name']
        self.address = args['address']

xiaoming = Student(ids=1,name='xiaoming',address='北京')
xiaohong = Student(ids=2,name='xiaohong',address='南京')

import json
with open('json.txt','w') as f:
    json.dump([xiaoming,xiaohong],f,default=lambda obj: obj.__dict__,ensure_ascii=False,indent=2,sort_keys=True)
[
  {
    "address": "北京",
    "ids": 1,
    "name": "xiaoming"
  },
  {
    "address": "南京",
    "ids": 2,
    "name": "xiaohong"
  }
]
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Data StructuresTutorialfunctionsObject-Orientedbasics
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.