Easton's Blog Easton's Blog
首页
  • 编程语言

    • Python
  • 框架

    • Django
  • Mdn (opens new window)
  • HTML
  • CSS
  • JavaScript
  • Mysql
  • PostgreSQL
  • Elasticsearch
  • MongoDB
  • Redis
  • 服务器命令
  • Docker
  • GIT
  • 摄影
  • 草稿
  • 归类方式

    • 分类
    • 标签
    • 归档
  • 关于博客

    • 博客教程
    • 友情链接
    • 关于
导航站
GitHub (opens new window)

Easton Yang

爱生活😊爱学习
首页
  • 编程语言

    • Python
  • 框架

    • Django
  • Mdn (opens new window)
  • HTML
  • CSS
  • JavaScript
  • Mysql
  • PostgreSQL
  • Elasticsearch
  • MongoDB
  • Redis
  • 服务器命令
  • Docker
  • GIT
  • 摄影
  • 草稿
  • 归类方式

    • 分类
    • 标签
    • 归档
  • 关于博客

    • 博客教程
    • 友情链接
    • 关于
导航站
GitHub (opens new window)
  • Python

    • Python学习

      • 特殊方法
      • 常用内置函数
      • 数据类型
      • with用法
      • Python面向对象
        • 面向对象案例
      • re正则
      • 线程
      • 进程
      • 协程
      • 装饰器
      • 堆队列heapq
      • 容器collections
      • 内置异常
      • 枚举
      • 好玩的函数
    • 代码

    • 数据结构与算法

  • Django

  • 后端
  • Python
  • Python学习
eastonyangxu
2023-09-04
目录

Python面向对象

abc 模块官方文档 (opens new window)

# 面向对象案例

from abc import ABC, abstractmethod


class People(ABC):

    def __init__(self, name):
        self._age = None
        self.type = ''
        self.name = name

    attribute = '属性值'

    @abstractmethod  # 如果有多个装饰器,该装饰器应该在最内层
    def hello(self):
        print('子类需要重写的方法!')

    def walking(self):
        print('{}会走路!'.format(self.type))

    def running(self):
        print('{}会奔跑!'.format(self.type))

    @property  # 定义了一个只读特征属性,不支持传参,调用方式类似于类变量调用
    def age(self):
        print('我是只读属性,类似于get_value()。')
        return self._age

    @age.setter
    def age(self, age):  # 接收一个值,类似于给属性赋值
        # 在这里可以对value进行各种判断,根据需要的场景
        if age < 0 or age > 150:
            print('年龄不符合!')
            return
        print('我是只写属性,类似于set_value()。设置的值:{}'.format(age))
        self._age = age

    def __x(self):
        print('私有方法,不能直接调用!')

    def __len__(self):
        return len(self.name)


class Teacher(People):
    def __init__(self, name):
        super().__init__(name)  # 这里需要放到最上面的位置
        self.type = '教师'

    def hello(self):
        print('这是teacher[{}]的hello!'.format(self.name))


class Student(People):
    def __init__(self, name):
        super().__init__(name)
        self.type = '学生'

    def hello(self):
        print('这是student[{}]的hello!'.format(self.name))

    def __str__(self):
        return '实现了__str__'


t = Teacher('A老师')
t.hello()
t.running()
t.walking()
t.age = -2  # set属性的使用
t.age = 10
print(t.age)  # 只读get属性的调用

t.attribute = '给属性赋值'  # 直接给属性赋值,不能进行逻辑处理。通过方法的方式给属性赋值,可以进行各种逻辑处理
print(t.attribute)

# t.__x()  # 私有方法不能直接调用,但是这是一个伪私有方法,python只是给__x方法重命名了
print(dir(t))  # 通过该函数可以查看所有的方法
t._People__x()  # 这个就是私有方法__x(),所以也是可以调用的,只是重命名了而已,不是真正意义上的私有方法!

print('=' * 40)

s1 = Student('A同学')  # 实例化对象,可以实例化多个对象。
s1.hello()
s2 = Student('B同学')
s2.hello()

# 类的专有方法():
# __init__ : 构造函数,在生成对象时调用
# __new__ : 一般在单例模式使用
# __del__ : 析构函数,释放对象时使用
# __repr__ : 打印,转换
# __setitem__ : 按照索引赋值
# __getitem__: 按照索引获取值
# __len__: 获得长度
# __cmp__: 比较运算
# __call__: 函数调用
# __add__: 加运算
# __sub__: 减运算
# __mul__: 乘运算
# __truediv__: 除运算
# __mod__: 求余运算
# __pow__: 乘方
# __str__: 字符串
# __enter__ 和 __exit__ ,在实现上下文的时候使用,实现的类一般用 with 来调用。可以参考study-with.py文件。
print(len(s2))  # 实现了 __len__
print(str(s2))


class Singleton:
    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, '_instance'):
            cls._instance = super(Singleton, cls).__new__(cls)
        return cls._instance


class TestSingleton(Singleton):
    def __init__(self, name):
        self.name = name

    def __str__(self):
        return self.name


ts = TestSingleton('A')
print(str(ts))  # A
ts1 = TestSingleton('B')
print(id(ts) == id(ts1))  # True
print(str(ts1))  # B
print(str(ts))  # B,如果不是单例模式,这里的值应该为A

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#Python
上次更新: 2023/09/04, 18:39:45
with用法
re正则

← with用法 re正则→

最近更新
01
攻略制作要点
07-18
02
摄影主题拍摄
07-18
03
延时摄影剧本
07-18
更多文章>
Theme by Vdoing | Copyright © 2023-2024 Easton Yang | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式