python中getattr函数使用方法 getattr实现工厂模式
看了下函数本身的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)

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

java工廠模式的好處:1、降低系統的耦合度;2、提高程式碼的復用性;3、隱藏物件的創建過程;4、簡化物件的創建過程;5、支援依賴注入;6、提供更好的性能;7、增強可測試性;8、支持國際化;9、促進開放封閉原則;10、提供更好的擴展性。詳細介紹:1、降低系統的耦合度,工廠模式透過將物件的創建過程集中到一個工廠類別中,降低了系統的耦合度;2、提高程式碼的複用性等等。

工廠模式用於解耦物件的建立過程,將其封裝在工廠類別中,使其與具體類別解耦。在Java框架中,工廠模式應用於:創建複雜物件(如Spring中的beans)提供物件隔離,增強可測試性和可維護性支援擴展,透過添加新工廠類別增加對新物件類型的支持

工廠模式在Go中,工廠模式允許建立對象,無需指定特定類別:定義一個表示對象的介面(例如Shape)。建立實作該介面的具體類型(例如Circle和Rectangle)。建立工廠類,根據給定的類型建立物件(例如ShapeFactory)。在客戶端程式碼中使用工廠類別建立物件。這種設計模式增強了程式碼的靈活性,無需直接耦合到特定類型。

Java工廠模式詳解:理解簡單工廠、工廠方法和抽象工廠的差異與應用場景引言在軟體開發過程中,面對複雜的物件建立和初始化過程,我們往往需要使用工廠模式來解決這個問題。 Java作為一種常用的物件導向程式語言,提供了多種工廠模式的實作方式。本文將詳細介紹Java工廠模式的三種常見實作方式:簡單工廠、工廠方法和抽象工廠,並且對它們的差異以及應用場景進行深入分析。一、

Python函數介紹:getattr函數的用法和範例在Python中,getattr()是一個內建函數,用來取得物件的屬性值。在不知道物件的屬性名稱的情況下,可以使用getattr()函數來動態存取屬性。本文將介紹getattr()函數的語法、用法和範例。 getattr()函數的語法如下:getattr(object,name[,default])參數

單例模式:透過函數重載提供不同參數的單例實例。工廠模式:透過函數重寫建立不同類型的對象,實現創建過程與特定產品類別的解耦。

導言PHP設計模式是一組經過驗證的解決方案,用於解決軟體開發中常見的挑戰。透過遵循這些模式,開發者可以創建優雅、健壯和可維護的程式碼。它們可協助開發者遵循SOLID原則(單一職責、開放-封閉、Liskov替換、介面隔離和依賴反轉),從而提高程式碼的可讀性、可維護性和可擴展性。設計模式的類型有許多不同的設計模式,每種模式都有其獨特的目的和優點。以下是一些最常用的php設計模式:單例模式:確保一個類別只有一個實例,並提供一種全域存取此實例的方法。工廠模式:建立一個對象,而不指定其確切類別。它允許開發者根據條件

Java工廠模式詳解:簡單工廠、工廠方法和抽象工廠工廠模式是一種常用的設計模式,它用於根據不同的需求動態創建對象,將對象的創建與使用分離,提高程式碼的可複用性和可擴展性。在Java中,工廠模式主要有三種形式:簡單工廠、工廠方法、抽象工廠。一、簡單工廠模式簡單工廠模式是最基本的工廠模式,也是最簡單的一種形式。它透過一個工廠類別來創建對象,根據不同的參數來決定創建哪
