Built-in Functions - 內置函數 - delattr() setattr() getattr() hasattr()

Built-in Functions - 內置函數 - delattr() setattr() getattr() hasattr()

https://docs.python.org/3/library/functions.html
https://docs.python.org/zh-cn/3/library/functions.html

需要執行對象裏的某個方法,或需要調用對象中的某個變量,但是由於種種原因我們無法確定這個方法或變量是否存在,這是我們需要用一個特殊的方法或機制要訪問和操作這個未知的方法或變量,這中機制就稱之爲反射 (自學習)。

Python 的反射的核心本質其實就是利用字符串的形式去對象 (模塊) 中操作 (查找/獲取/刪除/添加) 成員,一種基於字符串的事件驅動。

The Python interpreter has a number of functions and types built into it that are always available.
Python 解釋器內置了很多函數和類型,您可以在任何時候使用它們。

1. delattr(object, name)

This is a relative of setattr(). The arguments are an object and a string. The string must be the name of one of the object’s attributes. The function deletes the named attribute, provided the object allows it. For example, delattr(x, ‘foobar’) is equivalent to del x.foobar.
與 setattr() 相關的函數。參數是一個對象和一個字符串。該字符串必須是對象的某個屬性。如果對象允許,該函數將刪除指定的屬性。例如 delattr(x, ‘foobar’) 等價於 del x.foobar。

刪除屬性。

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function


class Dog():
    """A simple attempt to model a dog."""

    def __init__(self, name, age):
        """Initialize name and age attributes."""
        self.name = name
        self.age = age

    def sit(self):
        """Simulate a dog sitting in response to a command."""
        print(self.name.title() + " is now sitting.")

    def roll_over(self):
        """Simulate rolling over in response to a command."""
        print(self.name.title() + " rolled over!")


my_dog = Dog('willie', 6)
your_dog = Dog('lucy', 3)

print("My dog's name is " + my_dog.name.title() + ".")
print("My dog is " + str(my_dog.age) + " years old.")
my_dog.sit()

print("\nMy dog's name is " + your_dog.name.title() + ".")
print("My dog is " + str(your_dog.age) + " years old.")
your_dog.sit()

print()
print(hasattr(my_dog, "name"))
print(hasattr(my_dog, "sit"))
print()
print(hasattr(your_dog, "age"))
print(hasattr(your_dog, "roll_over"))
print()
print(hasattr(my_dog, "deep"))
print(hasattr(your_dog, "learning"))

print()
print(getattr(my_dog, "name"))
print(getattr(your_dog, "age"))
print()
print(getattr(my_dog, "sit"))
print(getattr(your_dog, "roll_over"))
print()
print(getattr(my_dog, "sit")())
print(getattr(your_dog, "roll_over")())
print()
print(getattr(my_dog, "deep", "forever"))
print(getattr(your_dog, "learning", "strong"))

print()
print(setattr(my_dog, "name", "java"))
print(getattr(my_dog, "name"))
print()
print(setattr(your_dog, "appearance", "beauty"))
print(getattr(your_dog, "appearance"))

print()
if hasattr(my_dog, 'gender'):
    print(getattr(my_dog, 'gender'))
else:
    setattr(my_dog, 'gender', "male")

print(getattr(my_dog, 'gender'))

print()
print(getattr(my_dog, "name"))
print(getattr(your_dog, "age"))
print()
print(delattr(my_dog, "name"))
print(delattr(your_dog, "age"))
print()
/usr/bin/python2.7 /home/strong/git_workspace/MonoGRNet/test.py
My dog's name is Willie.
My dog is 6 years old.
Willie is now sitting.

My dog's name is Lucy.
My dog is 3 years old.
Lucy is now sitting.

True
True

True
True

False
False

willie
3

<bound method Dog.sit of <__main__.Dog instance at 0x7f5cac27dbd8>>
<bound method Dog.roll_over of <__main__.Dog instance at 0x7f5cac27db90>>

Willie is now sitting.
None
Lucy rolled over!
None

forever
strong

None
java

None
beauty

male

java
3

None
None

<__main__.Dog instance at 0x7f5cac27dbd8>

Process finished with exit code 0

2. setattr(object, name, value)

This is the counterpart of getattr(). The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. For example, setattr(x, ‘foobar’, 123) is equivalent to x.foobar = 123.
此函數與 getattr() 相對應。其參數爲一個對象、一個字符串和一個任意值。字符串指定一個現有屬性或者新增屬性。函數會將值賦給該屬性,只要對象允許這種操作。例如,setattr(x, ‘foobar’, 123) 等價於 x.foobar = 123。

給 object 對象的 name 屬性賦值 value。如果對象原本存在給定的屬性 name,則 setattr 會更改屬性的值爲給定的 value。如果對象原本不存在屬性 name,setattr 會在對象中創建屬性,並賦值爲給定的 value。

一般先判斷對象中是否存在某屬性,如果存在則返回。如果不存在,則給對象增加屬性並賦值。很簡單的 if-else 判斷。

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function


class Dog():
    """A simple attempt to model a dog."""

    def __init__(self, name, age):
        """Initialize name and age attributes."""
        self.name = name
        self.age = age

    def sit(self):
        """Simulate a dog sitting in response to a command."""
        print(self.name.title() + " is now sitting.")

    def roll_over(self):
        """Simulate rolling over in response to a command."""
        print(self.name.title() + " rolled over!")


my_dog = Dog('willie', 6)
your_dog = Dog('lucy', 3)

print("My dog's name is " + my_dog.name.title() + ".")
print("My dog is " + str(my_dog.age) + " years old.")
my_dog.sit()

print("\nMy dog's name is " + your_dog.name.title() + ".")
print("My dog is " + str(your_dog.age) + " years old.")
your_dog.sit()

print()
print(hasattr(my_dog, "name"))
print(hasattr(my_dog, "sit"))
print()
print(hasattr(your_dog, "age"))
print(hasattr(your_dog, "roll_over"))
print()
print(hasattr(my_dog, "deep"))
print(hasattr(your_dog, "learning"))

print()
print(getattr(my_dog, "name"))
print(getattr(your_dog, "age"))
print()
print(getattr(my_dog, "sit"))
print(getattr(your_dog, "roll_over"))
print()
print(getattr(my_dog, "sit")())
print(getattr(your_dog, "roll_over")())
print()
print(getattr(my_dog, "deep", "forever"))
print(getattr(your_dog, "learning", "strong"))

print()
print(setattr(my_dog, "name", "java"))
print(getattr(my_dog, "name"))
print()
print(setattr(your_dog, "appearance", "beauty"))
print(getattr(your_dog, "appearance"))

print()
if hasattr(my_dog, 'gender'):
    print(getattr(my_dog, 'gender'))
else:
    setattr(my_dog, 'gender', "male")

print(getattr(my_dog, 'gender'))
/usr/bin/python2.7 /home/strong/git_workspace/MonoGRNet/test.py
My dog's name is Willie.
My dog is 6 years old.
Willie is now sitting.

My dog's name is Lucy.
My dog is 3 years old.
Lucy is now sitting.

True
True

True
True

False
False

willie
3

<bound method Dog.sit of <__main__.Dog instance at 0x7f8a626d5bd8>>
<bound method Dog.roll_over of <__main__.Dog instance at 0x7f8a626d5b90>>

Willie is now sitting.
None
Lucy rolled over!
None

forever
strong

None
java

None
beauty

male

Process finished with exit code 0

3. getattr(object, name[, default])

Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, ‘foobar’) is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.
返回對象命名屬性的值。name 必須是字符串。如果該字符串是對象的屬性之一,則返回該屬性的值。例如,getattr(x, ‘foobar’) 等同於 x.foobar。如果指定的屬性不存在,且提供了 default 值,則返回它,否則觸發 AttributeError。

獲取 object 對象的屬性的值。如果存在則返回屬性值,如果不存在分爲兩種情況:一種是沒有 default 參數時,會直接報錯。另一種給定了 default 參數,若對象本身沒有 name 屬性,則會返回給定的 default 值。如果給定的屬性 name 是對象的方法,則返回的是函數對象,需要調用函數對象來獲得函數的返回值,調用的話就是函數對象後面加括號,如 func 之於 func()。

如果給定的方法 func() 是實例函數,A 爲對象時,則寫成 getattr(A, ‘func’)()。

實例函數和類函數的區別,實例函數定義時,直接 def func(self):,這樣定義的函數只能是將類實例化後,用類的實例化對象來調用。而類函數定義時,需要用 @classmethod 來裝飾,函數默認的參數一般是 cls,類函數可以通過類來直接調用,而不需要對類進行實例化。

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function


class Dog():
    """A simple attempt to model a dog."""

    def __init__(self, name, age):
        """Initialize name and age attributes."""
        self.name = name
        self.age = age

    def sit(self):
        """Simulate a dog sitting in response to a command."""
        print(self.name.title() + " is now sitting.")

    def roll_over(self):
        """Simulate rolling over in response to a command."""
        print(self.name.title() + " rolled over!")


my_dog = Dog('willie', 6)
your_dog = Dog('lucy', 3)

print("My dog's name is " + my_dog.name.title() + ".")
print("My dog is " + str(my_dog.age) + " years old.")
my_dog.sit()

print("\nMy dog's name is " + your_dog.name.title() + ".")
print("My dog is " + str(your_dog.age) + " years old.")
your_dog.sit()

print()
print(hasattr(my_dog, "name"))
print(hasattr(my_dog, "sit"))
print()
print(hasattr(your_dog, "age"))
print(hasattr(your_dog, "roll_over"))
print()
print(hasattr(my_dog, "deep"))
print(hasattr(your_dog, "learning"))

print()
print(getattr(my_dog, "name"))
print(getattr(your_dog, "age"))
print()
print(getattr(my_dog, "sit"))
print(getattr(your_dog, "roll_over"))
print()
print(getattr(my_dog, "sit")())
print(getattr(your_dog, "roll_over")())
print()
print(getattr(my_dog, "deep", "forever"))
print(getattr(your_dog, "learning", "strong"))
/usr/bin/python2.7 /home/strong/git_workspace/MonoGRNet/test.py
My dog's name is Willie.
My dog is 6 years old.
Willie is now sitting.

My dog's name is Lucy.
My dog is 3 years old.
Lucy is now sitting.

True
True

True
True

False
False

willie
3

<bound method Dog.sit of <__main__.Dog instance at 0x7f19681b9bd8>>
<bound method Dog.roll_over of <__main__.Dog instance at 0x7f19681b9b90>>

Willie is now sitting.
None
Lucy rolled over!
None

forever
strong

Process finished with exit code 0

4. hasattr(object, name)

The arguments are an object and a string. The result is True if the string is the name of one of the object’s attributes, False if not. (This is implemented by calling getattr(object, name) and seeing whether it raises an AttributeError or not.)
該參數是一個對象和一個字符串。如果字符串是對象的屬性之一的名稱,則返回 True,否則返回 False。(此功能是通過調用 getattr(object, name) 看是否有 AttributeError 異常來實現的。)

判斷 object 對象中是否存在 name 屬性,對於 Python 的對象而言,屬性包含變量和方法。name 參數是 string 類型,不管是要判斷變量還是方法,其名稱都以字符串形式傳參。

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function


class Dog():
    """A simple attempt to model a dog."""

    def __init__(self, name, age):
        """Initialize name and age attributes."""
        self.name = name
        self.age = age

    def sit(self):
        """Simulate a dog sitting in response to a command."""
        print(self.name.title() + " is now sitting.")

    def roll_over(self):
        """Simulate rolling over in response to a command."""
        print(self.name.title() + " rolled over!")


my_dog = Dog('willie', 6)
your_dog = Dog('lucy', 3)

print("My dog's name is " + my_dog.name.title() + ".")
print("My dog is " + str(my_dog.age) + " years old.")
my_dog.sit()

print("\nMy dog's name is " + your_dog.name.title() + ".")
print("My dog is " + str(your_dog.age) + " years old.")
your_dog.sit()
print()
print(hasattr(my_dog, "name"))
print(hasattr(my_dog, "sit"))
print()
print(hasattr(your_dog, "age"))
print(hasattr(your_dog, "roll_over"))
print()
print(hasattr(my_dog, "deep"))
print(hasattr(your_dog, "learning"))
/usr/bin/python2.7 /home/strong/git_workspace/MonoGRNet/test.py
My dog's name is Willie.
My dog is 6 years old.
Willie is now sitting.

My dog's name is Lucy.
My dog is 3 years old.
Lucy is now sitting.

True
True

True
True

False
False

Process finished with exit code 0
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章