谈谈Python的内建方法

本文详细探讨了Python中的内建方法,包括__class__、__delattr__/__getattribute__/__setattr__、__dict__、__doc__/__format__/__str__/__repr__/__module__、__hash__、__new__/__init__、__reduce__/__reduce_ex__、__sizeof__和__subclasshook__。这些方法在Python类和对象中扮演着关键角色,涉及类型检查、属性操作、内存大小、哈希计算等方面。文章通过实例解析了它们的用途和潜在影响,提醒开发者在生产环境中谨慎使用某些方法,如__hash__,并预告了后续将单独讲解__new__和__subclasshook__。
摘要由CSDN通过智能技术生成

查看类包含的方法

# coding=utf-8
from pprint import pprint as pp


class A(object):
    pass


pp(dir(A))

下面是打印内容,也就是后面探讨的内容,下面让我们一起来看看Python类对象的内建方法都有哪些作用:

['__class__',
 '__delattr__',
 '__dict__',
 '__doc__',
 '__format__',
 '__getattribute__',
 '__hash__',
 '__init__',
 '__module__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__']

1.__class__方法

一句话总结:__class__方法等同于Python的内建方法type

# coding=utf-8
from pprint import pprint as pp


class A(object):
    pass

print A.__class__, type

打印结果:

<type 'type'> <type 'type'>

这意味着A.__class__和Python的内建方法type是同一个内建方法,所以让我们看看type的这个注释:

    def __init__(cls, what, bases=None, dict=None): # known special case of type.__init__
        """
        type(object) -> the object's type
        type(name, bases, dict) -> a new type
        # (copied from class doc)
        """
        pass
  1. type(object) ,返回A的类型,这种用法大家都经常使用;
  2. type(name, bases, dict),生成新的类型,用于代码中动态生成新的类型,参数name用于指定新生成的类名,参数bases,用于指定继承父类的元组,dict可以动态的为新生成的类指定属性,下面来个例子,用于证明__class__方法与type等效:
# coding=utf-8
from pprint import pprint as pp


class A(object):
    def __init__(self):
        self.PropertyA = 1


class B(object):
    def __init__(self):
        self.PropertyB = 2

    def B_method(self)
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值