Home Backend Development Python Tutorial Python中getattr函数和hasattr函数作用详解

Python中getattr函数和hasattr函数作用详解

Jun 16, 2016 am 08:47 AM
getattr python

hasattr(object, name)

作用:判断对象object是否包含名为name的特性(hasattr是通过调用getattr(ojbect, name)是否抛出异常来实现的)。

示例:

>>> hasattr(list, 'append')
True >>> hasattr(list, 'add')
False 
getattr(object,name,default):
Copy after login

作用:返回object的名称为name的属性的属性值,如果属性name存在,则直接返回其属性值;如果属性name不存在,则触发AttribetError异常或当可选参数default定义时返回default值。

这个方法最主要的作用是实现反射机制。也就是说可以通过字符串获取方法实例。这样,你就可以把一个类可能要调用的方法放在配置文件里,在需要的时候动态加载。

下面我们使用小例子来说明它们的用法:

import func_file #自定义python模块
cs=input('请输入要访问的URL:')
if cs=='loggin':
func_file.loggin()
if cs =='home':
func_file.home()
if cs =='':
pass#以下省略 
Copy after login

当我定义一个自定义模块,去调用其中的方法的时候,使用if去判断时,如果模块内用很多方法,会大大影响开发的效率,代码冗余差,显然这是不可取的。下面我们使用hasattr()函数来实现我们的需求:

示例如下:

import func_file #自定义python模块,需事先存在
def run():
while True:
cs=input('请输入要访问的URL:')
#hasattr利用字符串的形式去对象(模块)中操作(寻找)成员
if hasattr(func_file,cs): #判断用户输入的URL是否在func_file模块中
func=getattr(func_file,cs) #有则将func_file模块下的cs函数赋值 
func() #等同于执行func_file模块下的cs函数
else:
print('404')#定义错误页面
run() 
Copy after login

我们导入一个自定义模块后,gatattr可以根据输入的内容动态加载,利用hasattr()函数来判断用户输入的是否存在,不存在则调用自定义方法。

是不是感觉和我们打开网址URL很类似啊!

上一个示例有一个问题,在实际情况中,我们的功能函数可能存放在很多模块中,每一个都需要单独导入,那我们可不可以利用getattr()函数去动态加载模块呢?当然可以啦

请看示例:

def run():
while True:
cs=input('请输入:')
v,k=cs.split('/') #获得输入的模块和模块的方法
obj=__import__('lib.'+v,fromlist=True) #调用lib目录下的模块fromlist=True按路径连接的方式导入
if hasattr(obj,k):
f= getattr(obj,k)
f()
else:
print('404')
if __name__ == '__main__':
run() 
Copy after login

是不是感到getattr很强大啊。其实,getattr()就是实现python反射的一块积木,结合其它方法如setattr(),dir() 等,我们可以还可以做出很多有趣的事情。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

See all articles