曦远 (DealiAxy)一份私人的文字刊物

StarBlog
返回文章列表折页手记阅读全文
Python

Python Pitfalls: Passing and Using Class vs. Class Object Type Parameters

Preface For beginners, Python is indeed simple and easy to use. After all, it's a dynamically typed language—you can use things without defining them, and freely converting between types couldn't be more convenient. So using Python to write small scripts, crawlers, and the like is no problem. However, once you use it to develop a slightly larger project, such as building a web application, you'll run into some issues. People who generally lack experience will fall into certain pitfalls. = =... Pitfalls Let's talk about the pitfalls first. Function parameter types are one pitfall, and classes versus class objects are another. Although I had figured this out when using other statically typed languages (such as C

曦远 (DealiAxy)约 9 分钟
目录3 个章节

Preface

For beginners, Python is indeed simple and easy to use. After all, it's a dynamically typed language—you can use things without defining them, and freely converting between types couldn't be more convenient. So using Python to write small scripts, crawlers, and the like is no problem. However, once you use it to develop a slightly larger project, such as building a web application, you'll run into some issues. People who generally lack experience will fall into certain pitfalls. = =...

Pitfalls

Let's talk about the pitfalls first. Function parameter types are one pitfall, and classes versus class objects are another. Although I had figured this out when using other statically typed languages (such as C#/Java), switching to dynamically typed Python always leaves one a bit puzzled.

Example

Let me illustrate with code.

First, define two classes, both inheriting from the built-in Exception class, which means these two classes are exception classes.

class Error1(Exception):
    def __str__(self):
        return 'error1'


class Error2(Exception):
    def __init__(self):
        print('error2 init')

    def __str__(self):
        return 'error2'

Then define methods for handling exceptions:

def error(err: object):
    print(f'err:{err.__str__()}')

def error2(err: Exception):
    print(err)

Next is the test code:

try:
    raise Error1
except Error1 as e:
    error(e)

if 1 != 2:
    error(Error2)

Running result:

err:error1
  File "/home/test.py", line 33, in <module>
    error(Error2)
  File "/home/test.py", line 19, in error
    print(f'err:{err.__str__()}')
TypeError: __str__() missing 1 required positional argument: 'self'

The result of the first error() is fine, but the second one then threw an exception. Let's look at the error message first: TypeError: __str__() missing 1 required positional argument: 'self'. The self parameter was not provided, because this argument is not an instance of the Error2 class, so naturally there is no self parameter.

At this point you should have some idea: when calling the error(Error2) method, the Error2 argument passed in is actually the Error2 type itself, not an object of it. It's a bit magical that you can actually use a type as an argument.

So how do we solve this? It's simple: just pass in an object of Error2. The code is as follows:

if 1 != 2:
    error(Error2())

Running result

error2 init
err:error2

No problem now. There's still an error2 method in the code above that hasn't been used. Let's try it.

error2(Error2)
error2(Error2())

Running result

<class '__main__.Error2'>
error2 init
error2

As you can see, when using print(Object), if it's a type, it prints information about that type; only when it's an object of the type will it print the result returned by Object.__str__(). Once you understand it, it's actually quite simple. But Python doesn't restrict function parameters. Even if you add type hints to methods, they only serve as hints and don't actually enforce restrictions or implicit conversions. So sometimes after writing code for a long time and getting dizzy, it's easy to fall into the dynamic typing pit T_T...

As is international custom, here's an image:

_EOF_

Python Pitfalls: Passing and Using Class vs. Class Object Type Parameters

本文作者:
程序设计实验室
版权声明:
本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!

相关文章

编写爬虫自动下载王者荣耀官网上好看的壁纸

前言 偶然间发现王者荣耀的官网上发布了这么多好看的壁纸。 地址:http://pvp.qq.com/web201605/wallpaper.shtml 看了一下,每一张都挺喜欢的,而且还有十多页,一张一张去慢慢下载肯定不是作为一个Geeker的正确姿势。 由于最近python用得比较多,所以看到什么好玩的就想爬虫下载下来,所以看到这么多好看图片,我又“熟练”地掏出了python。 分析 这个网站长

2021-12-18 · Python · 约 1 分钟

使用Python+FFMPEG实现视频分割与合并

前言 日常中偶尔会遇到需要简单剪辑处理视频的场景,以前我可能会拿出PR来剪辑一下,(别跟我说国产那些软件,剪辑完视频强制加上广告片头片尾恶心的一批),但是PR毕竟太重量级,剪个简单的视频都要花不少时间,直到我发现了FFmpeg…… 这个FFmpeg真的是神器,免费开源功能强大,好像很多软件都是基于这个开发的,它本身提供了命令行接口就已经能满足我们日常的简单视频处理需求,我用来简单处理视频分割、合并

2022-05-27 · Python · 约 1 分钟

Python数据展示 - 生成表格图片

前言 前一篇文章介绍了推送信息到企业微信群里,其中一个项目推送的信息是使用Python自动生成的表格,本文来讲讲如何用Python生成表格图片。 选一个合适库 Python最大的优点就是第三方库丰富,基本你要什么功能,都能找到别人实现好的库,几行代码一调用就完事了。 Pytable 项目地址:https://github.com/HiroshiARAKI/pytable 最先找到的是日本人开发的p

2022-04-09 · Python · 约 1 分钟

讨论

共 0 条

良言一句三冬暖,恶语伤人六月寒。

加载评论中…