Home Backend Development Python Tutorial python中getattr函数使用方法 getattr实现工厂模式

python中getattr函数使用方法 getattr实现工厂模式

Jun 16, 2016 am 08:45 AM
getattr Factory pattern

看了下函数本身的doc

复制代码 代码如下:

getattr(object, name[, default]) -> value

Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
When a default argument is given, it is returned when the attribute doesn't
exist; without it, an exception is raised in that case.

解释的很抽象 告诉我这个函数的作用相当于是

object.name

试了一下getattr(object,name)确实和object.name是一样的功能.只不过这里可以把name作为一个变量去处理书上的例子很好的说明了这个函数的功用,使用getattr可以轻松实现工厂模式。

例:一个模块支持html、text、xml等格式的打印,根据传入的formate参数的不同,调用不同的函数实现几种格式的输出

复制代码 代码如下:

import statsout
def output(data, format="text"):                          
    output_function = getattr(statsout, "output_%s" %format)
    return output_function(data)
[code]
这个例子中可以根据传入output函数的format参数的不同 去调用statsout模块不同的方法(用格式化字符串实现output_%s)

返回的是这个方法的对象 就可以直接使用了 如果要添加新的格式 只需要在模块中写入新的方法函数 在调用output函数时使用新的参数就可以使用不同的格式输出

确实很方便


为了加深对getattr函数的理解 转载一篇英文的说明

Python's getattr function is used to fetch an attribute from an object, using a string object instead of an identifier to identify the attribute. In other words, the following two statements are equivalent:

[code]
value = obj.attribute
value = getattr(obj, "attribute")
If the attribute exists, the corresponding value is returned. If the attribute does not exist, you get an AttributeError exception instead.

The getattr function can be used on any object that supports dotted notation (by implementing the __getattr__ method). This includes class objects, modules, and even function objects.

path = getattr(sys, "path")
doc = getattr(len, "__doc__")
The getattr function uses the same lookup rules as ordinary attribute access, and you can use it both with ordinary attributes and methods:

result = obj.method(args)

func = getattr(obj, "method")
result = func(args)
or, in one line:

result = getattr(obj, "method")(args)
Calling both getattr and the method on the same line can make it hard to handle exceptions properly. To avoid confusing AttributeError exceptions raised by getattr with similar exceptions raised inside the method, you can use the following pattern:

try:
    func = getattr(obj, "method")
except AttributeError:
    ... deal with missing method ...
else:
    result = func(args)
The function takes an optional default value, which is used if the attribute doesn't exist. The following example only calls the method if it exists:

func = getattr(obj, "method", None)
if func:
    func(args)
Here's a variation, which checks that the attribute is indeed a callable object before calling it.

func = getattr(obj, "method", None)
if callable(func):
    func(args)

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
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)

What are the application scenarios of factory pattern in java framework? What are the application scenarios of factory pattern in java framework? Jun 01, 2024 pm 04:06 PM

The factory pattern is used to decouple the creation process of objects and encapsulate them in factory classes to decouple them from concrete classes. In the Java framework, the factory pattern is used to: Create complex objects (such as beans in Spring) Provide object isolation, enhance testability and maintainability Support extensions, increase support for new object types by adding new factory classes

What are the benefits of java factory pattern What are the benefits of java factory pattern Dec 25, 2023 pm 05:40 PM

The benefits of the Java factory pattern: 1. Reduce system coupling; 2. Improve code reusability; 3. Hide the object creation process; 4. Simplify the object creation process; 5. Support dependency injection; 6. Provide better performance; 7. Enhance testability; 8. Support internationalization; 9. Promote the open and closed principle; 10. Provide better scalability. Detailed introduction: 1. Reduce the coupling of the system. The factory pattern reduces the coupling of the system by centralizing the object creation process into a factory class; 2. Improve the reusability of code, etc.

How to apply factory pattern in Golang How to apply factory pattern in Golang Apr 04, 2024 am 11:33 AM

Factory Pattern In Go, the factory pattern allows the creation of objects without specifying a concrete class: define an interface (such as Shape) that represents the object. Create concrete types (such as Circle and Rectangle) that implement this interface. Create a factory class to create objects of a given type (such as ShapeFactory). Use factory classes to create objects in client code. This design pattern increases the flexibility of the code without directly coupling to concrete types.

Introduction to Python functions: usage and examples of getattr function Introduction to Python functions: usage and examples of getattr function Nov 04, 2023 pm 01:39 PM

Introduction to Python functions: Usage and examples of getattr function In Python, getattr() is a built-in function used to obtain the attribute value of an object. Without knowing the object's attribute name, you can use the getattr() function to dynamically access the attribute. This article will introduce the syntax, usage and examples of the getattr() function. The syntax of the getattr() function is as follows: getattr(object,name[,default]) parameters

An in-depth analysis of the Java factory pattern: distinguishing and applying the differences between simple factories, factory methods and abstract factories An in-depth analysis of the Java factory pattern: distinguishing and applying the differences between simple factories, factory methods and abstract factories Dec 28, 2023 pm 03:09 PM

Detailed explanation of Java Factory Pattern: Understand the differences and application scenarios of simple factories, factory methods and abstract factories Introduction In the software development process, when faced with complex object creation and initialization processes, we often need to use the factory pattern to solve this problem. As a commonly used object-oriented programming language, Java provides a variety of factory pattern implementations. This article will introduce in detail the three common implementation methods of the Java factory pattern: simple factory, factory method and abstract factory, and conduct an in-depth analysis of their differences and application scenarios. one,

The application of singleton mode and factory mode in C++ function overloading and rewriting The application of singleton mode and factory mode in C++ function overloading and rewriting Apr 19, 2024 pm 05:06 PM

Singleton pattern: Provide singleton instances with different parameters through function overloading. Factory pattern: Create different types of objects through function rewriting to decouple the creation process from specific product classes.

Detailed explanation of Java factory pattern: simple factory, factory method and abstract factory Detailed explanation of Java factory pattern: simple factory, factory method and abstract factory Dec 28, 2023 am 10:23 AM

Detailed explanation of Java factory pattern: simple factory, factory method and abstract factory The factory pattern is a commonly used design pattern. It is used to dynamically create objects according to different needs, separate the creation and use of objects, and improve the reusability and use of code. Scalability. In Java, there are three main forms of factory pattern: simple factory, factory method and abstract factory. 1. Simple factory model The simple factory model is the most basic factory model and the simplest form. It creates objects through a factory class and determines which object to create based on different parameters.

Understand the factory pattern in PHP object-oriented programming Understand the factory pattern in PHP object-oriented programming Aug 10, 2023 am 10:37 AM

Understanding the Factory Pattern in PHP Object-Oriented Programming The factory pattern is a commonly used design pattern that is used to decouple the creation and use of objects during the process of creating objects. In PHP object-oriented programming, the factory pattern can help us better manage the creation and life cycle of objects. This article will introduce the factory pattern in PHP in detail through code examples. In PHP, we can implement the object creation and initialization process by using the factory pattern instead of directly using the new keyword. The advantage of this is that if changes need to be made in the future

See all articles