python的魔法属性记录

参考链接:

1)https://www.mdnice.com/writing/3a552207f3da4ecaa0121ceb82cafae5

2)https://www.cnblogs.com/cwp-bg/p/9856291.html

__dict__

1)作用:显示类或对象中的所有属性

2)实例:

class Student:
    def __init__(self,name,age):
        self.name = name
        self._age = age       # 一个下划线加变量名表示私有属性,一般情况下,外界无法访问
        
    @property
    def age(self):
        return self._age
    
# 1.显示类的所有属性
print(Student.__dict__)
# 2.显示对象中的所有属性
s = Student('petty',19)
print(s.__dict__)
------------------------------------
mappingproxy(
    {'__module__': '__main__',
     '__init__': <function Student.__init__ at 0x00000254CA789300>,
     'age': <property object at 0x00000254CA772430>,
     '__dict__': <attribute '__dict__' of 'Student' objects>, 
     '__weakref__': <attribute '__weakref__' of 'Student' objects>, 
     '__doc__': None
    })
-------------------------------------
{'name': 'petty', '_age': 19}

__doc__

1)作用:描述类的基本信息,即注释信息

2)实例:

class Foo:
    """做个测试"""
    pass
print(Foo.__doc__)
---------------------
运行结果:做个测试

__module__

1)作用:表示当前操作的对象所在的模块

2)实例:

# oop.py
class Foo:
    pass

# main.py
from opp import Foo
f = Foo()
print(f.__module__)
--------------------
运行结果:opp

__class__

1)作用:表示当前操作的对象的类是什么

2)实例:

# oop.py
class Foo:
    pass

# main.py
from opp import Foo
f = Foo()
print(f.__class__)
---------------------
运行结果:<class 'oop.Foo'>

__slots__

1)作用:限制动态绑定属性和方法,只有__slots__中包含的属性才能赋值。

2)实例:

class Student:
    __slots__ = {'name', 'age','weight'}
    def __init__(self,name,age):
        self.name = name
        self.age = age

s = Studeng('petty',19)
s.weight = 45
s.height = 156
-------------------------
Traceback (most recent call last):
  File "<pyshell#24>", line 1, in <module>
    s.height = 156
AttributeError: 'Student' object has no attribute 'height'
        

__mro__

1)作用:记录类继承的关系,是元祖类型

2)实例:

class Config(dict): pass

print(Config.__mro__)

>>>
(<class '__main__.Config'>, <class 'dict'>, <class 'object'>)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值