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

猜你喜欢

转载自blog.csdn.net/chengyq116/article/details/93525550