Python的程序结构[2] -> 类/Class[0] -> 类的特殊属性

本文介绍了Python中类的一些特殊属性,包括__name__、__doc__、__bases__、__dict__、__module__和__class__。通过具体代码示例展示了如何使用这些属性来获取类的相关信息。

类的特殊属性 / Special Property of Class


Python 中通过 class 进行类的定义,类可以实例化成实例并利用实例对方法进行调用。

类中还包含的一些共有的特殊属性。

 

特殊类属性

含义

__name__

类的名字(字符串)

__doc__ 

类的文档字符串

__bases__

类的所有父类组成的元组

__dict__

类的属性组成的字典

__module__

类所属的模块

__class__

类对象的类型

 

 1 class Foo():
 2     """
 3     This is the text that can be called by __doc__
 4     """
 5     def __init__(self):
 6         self.foo = None
 7 
 8     def foo_method(self):
 9         self.foom = True
10 
11 print('>>>', Foo.__name__)
12 print('>>>', Foo.__doc__)
13 print('>>>', Foo.__bases__)
14 print('>>>', Foo.__dict__)
15 print('>>>', Foo.__module__)
16 print('>>>', Foo.__class__)

上面的代码定义了一个 Foo 类,并对类的基本特殊属性依次进行调用,最后得到结果如下,

>>> Foo
>>> 
    This is the text that can be called by __doc__
    
>>> (<class 'object'>,)
>>> {'__dict__': <attribute '__dict__' of 'Foo' objects>, '__doc__': '\n    This is the text that can be called by __doc__\n    ', '__weakref__': <attribute '__weakref__' of 'Foo' objects>, '__init__': <function Foo.__init__ at 0x0301F930>, '__module__': '__main__', 'foo_method': <function Foo.foo_method at 0x0305C348>}
>>> __main__
>>> <class 'type'>

 

转载于:https://www.cnblogs.com/stacklike/p/8098067.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值