欢迎访问宙启技术站
智能推送

学习Python中内建对象(object())的方法和属性

发布时间:2023-12-26 22:13:40

Python中的内建对象 object 是所有类的基类,它定义了一些基本的方法和属性,可以在任何类中使用。下面详细介绍一些 object 的方法和属性。

1.方法:

(1)dir():返回对象的所有属性和方法的列表。

例子:

class Person:
    name = 'Alice'
    age = 18
    
p = Person()
print(dir(p))

输出结果为:

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'name']

(2)__delattr__(self, name):删除指定属性。

例子:

class Person:
    name = 'Alice'
    age = 18
    
p = Person()
delattr(p, 'age')
print(p.age)  # AttributeError: 'Person' object has no attribute 'age'

(3)__getattribute__(self, name):获取指定属性的值。

例子:

class Person:
    name = 'Alice'
    age = 18
    
p = Person()
print(p.__getattribute__('name'))  # Alice

(4)__setattr__(self, name, value):设置指定属性的值。

例子:

class Person:
    name = 'Alice'
    age = 18
    
p = Person()
p.__setattr__('age', 20)
print(p.age)  # 20

(5)__dir__(self):返回对象的所有属性和方法的列表。

例子:

class Person:
    name = 'Alice'
    age = 18
    
p = Person()
print(p.__dir__())

输出结果与 dir() 方法相同。

2.属性:

(1)__class__:对象所属的类。

例子:

class Person:
    name = 'Alice'
    age = 18
    
p = Person()
print(p.__class__)  # <class '__main__.Person'>

(2)__dict__:对象的属性字典。

例子:

class Person:
    name = 'Alice'
    age = 18
    
p = Person()
print(p.__dict__)  # {'name': 'Alice', 'age': 18}

(3)__doc__:对象的文档字符串。

例子:

class Person:
    """
    This is a person class.
    """
    name = 'Alice'
    age = 18
    
p = Person()
print(p.__doc__)  # This is a person class.

(4)__module__:对象所属的模块。

例子:

class Person:
    name = 'Alice'
    age = 18
    
p = Person()
print(p.__module__)  # __main__

(5)__weakref__:对象的弱引用。

例子:

class Person:
    name = 'Alice'
    age = 18
    
p = Person()
print(p.__weakref__)  # None

在以上例子中,介绍了一些 object 的方法和属性,包括 dir()、__delattr__()、__getattribute__()、__setattr__()、__dir__() 和 class、__dict__、__doc__、__module__、__weakref__。这些方法和属性可以帮助我们对对象的属性和方法进行操作和获取相应的信息。