9.4 内置方法

Python对于类有一组内置的方法,例如:

>>> class Student:
...     pass
...
>>> s = Student()
>>> type(s)
<class '__main__.Student'>
>>> dir(s)
['__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__']

这些方法,都具有特殊用途,例如:

  • __init__ : 初始化函数
  • __dict__ : 以字典方式返回类或实例的属性,如果是类对象,则返回类的所有属性;如果是实例对象,则返回实例的所有变量。
  • __doc__ : 类的文档字符串
  • __name__ : 类名
  • __bases__ : 类的所有父类构成元素(包含了一个由所有父类组成的元组)
  • __str__ : 打印输出

灵活的使用这些方法,能够提供很多实用的功能。

例如:9.3-内置方法.py

# 内置方法


class Student:
    """
    Student类说明文档
    """

    # 带参数的构造函数
    def __init__(self, name, sex, age):
        self.name = name
        self.sex = sex
        self.age = age

    def __str__(self):
        return '学生:{},性别:{},年龄:{}。'.format(self.name, self.sex, self.age)

    # 定义方法
    def bao_ming(self):
        print('学生{}报名。'.format(self.name))


# 带参数的构造函数,创建实例
s1 = Student('lisi', 'male', 24)
print('s1.__dict__:', s1.__dict__)
print('Student.__dict__:', Student.__dict__)
print('s1.__doc__:', s1.__doc__)
print('Student.__name__:', Student.__name__)
print('Student.__bases__:', Student.__bases__)
print(s1)

运行结果为:

s1.__dict__: {'name': 'lisi', 'sex': 'male', 'age': 24}
Student.__dict__: {'__module__': '__main__', '__doc__': '\n 
   Student类说明文档\n    ', '__init__': <function Student.__init__ at 0x0000024530945828>, '__str__': <function Student.__str__ at 0x00000245309458B8>, 'bao_ming': <function Student.bao_ming at 0x0000024530945948>, '__dict__': <attribute '__dict__' of 'Student' objects>, '__weakref__': <attribute '__weakref__' of 'Student' objects>}
s1.__doc__:
    Student类说明文档

Student.__name__: Student
Student.__bases__: (<class 'object'>,)
学生:lisi,性别:male,年龄:24。