Python学习笔记(一)

Python中一切皆对象,函数和类也是对象,属于Python的一等公民。

  1. 对象可以赋值给一个变量
  2. 对象可以添加到集合对象中
  3. 对象可以作为参数传递给函数
  4. 对象可以当做函数的返回值

对象的三个特征:1、身份(id());2、类型;3、值

type->int>1

type>class->obj

object是最顶层基类

type也是一个类,同时type也是对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
a = 1 
b = "abc"
print(type(1))   #  <class 'int'>
print(type(int)) #  <class 'type'>
print(type(b))   # <class 'str'>
print(type(str))  # <class 'type'>
 
class Student(object):
    pass
 
class MyStudent(Student):
    pass
 
stu = Student()
 
print(type(stu))  # <class '__main__.Student'>
print(type(Student))  # <class 'type'>
print(int.__bases__)  $ (<class 'object'>,)
print(str.__bases__)  # (<class 'object'>,)
print(Student.__bases__)  # (<class 'object'>,)
print(MyStudent.__bases__)  # (<class '__main__.Student'>,)
print(type.__bases__)  # (<class 'object'>,)
print(object.__bases__)  # ()
print(type(object))  # (<class 'object'>,)
print(type(type))  # <class 'type'>
 
def aa():
    pass
print(aa.__class__)  # <class 'function'>print(type(aa.__class__))  # <class 'type'>

Python中常见的内置类型:

  • None(全局只有一个)
  • 数值迭代类型
    • int
    • float
    • complex
    • bool
  • 序列类型映射(dict)
    • list
    • bytes、bytearray、memoryview(二进制序列)
    • range
    • tuple
    • str
    • array
  • 集合上下文管理类型(with)
    • set
    • frozenset
  • 其它
    • 模块类型
    • class和实例
    • 函数类型
    • 方法类型
    • 代码类型
    • object对象
    • type类型
    • ellipsis类型
    • notimplemented类型

魔法函数(魔法方法)的存在是为了被 Python 解释器调用的,你自己并不需要调用它们。魔方方法增强了自定义类的功能,使开发者能够直接使用原生的方法扩充自定义类。


鸭子类型也是Python这种动态语言的一种特性,在鸭子类型中,关注的不是对象的类型本身,而是它是如何使用的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Cat(object):
    def say(self):
        print("i am a cat")
class Dog(object):
    def say(self):
        print("i am a dog")
class Duck(object):
    def say(self):
        print("i am a duck")
 
animal_list = [Cat, Duck, Dog]
for animal in animal_list:
    animal().say()
 
i am a cat
i am a duck
i am a dog

抽象基类用途: 1、判定某个对象的类型(instance()方法);2、强制某个子类必须实现某些方法。

实例方法可由实例调用,但类也可以调用(不推荐),需要手动给 self 参数传值。类方法实例(不推荐)与类都可以调用。静态方法可由实例与类调用。

私有变量可以使用_类名__变量名调用,私有变量使用这种小技巧起到保护作用。

自省是通过一定的机制查询到对象的内部机构,Python提供了__dict__这个魔法方法去查询对象属性,该方法以字典形式的返回值展示出对象内部的属性与值。同时Python还提供了dir()方法,该方法以列表形式放回对象支持的所有属性。

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class User(object):
    def __init__(self, age):
        self.__age = age
 
    def get_age(self):
        return self.__age
 
if __name__ == '__main__':
    user = User(30)
    print(user.__dict__)
    print(dir(user))
 
{'_User__age': 30}
['_User__age', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'get_age'] 

多继承关系时,super()函数调用顺序是按照__mro__方法返回的顺序去依次调用的。在Python中多继承推荐使用Mixin模式,该模式有以下特点:1、Mixin类功能单一;2、不和基类关联,可以和任意基类组合,基类可以不和Mixin关联就能初始化成功;3、在Mixin中不要使用super这种用法。

 


上下文管理器协议,关键魔法方法:__enter__、__exit__,当然使用contextlib提供的装饰器结合生成器函数也可实现上下文管理协议

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Sample(object):
    def __enter__(self):
        # 获取资源
        print("enter")
        return self  # 获取资源后返回
 
    def __exit__(self, exc_type, exc_val, exc_tb):
        # 释放资源
        print("exit")
 
    def do_something(self):
        print("doing something")
 
 
with Sample() as sample:
    sample.do_something()
 
enter
doing something
exit
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import contextlib
 
 
@contextlib.contextmanager
def file_open(filename):
    print("file open")
    yield
    print("file end")
 
 
with file_open("test.txt") as f_opened:
    print("file processing")
 
file open
file processing
file end

 

posted @   为什么不是这样呢  阅读(8)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
点击右上角即可分享
微信分享提示