Python 常用的魔法方法汇总

python 魔法方法

1. __ init __()

用于实例化类传值使用

2. __ str __()

如果要把一个类的实例变成 str,就需要实现特殊方法__str__()

class Student(object):
    def __init__(self,id,name,age):
        self.id=id
        self.name=name
        self.age=age
 
    def __str__(self):
        return "学号:{}--姓名:{}--年龄{}".format(self.id,self.name,self.age)
    
s=Student(111,"Bob",18)
print(s)

3. __ new __(cls)

实例化类先调用__ new __ (cls)方法后调用__ init __方法

class CapStr(str):
    def __new__(cls, string):
        self_in_init = super().__new__(cls, string)
        print(id(self_in_init))
        return self_in_init
    def __init__(self,string):
        print(id(self))
 
a = CapStr("I love China!")
print(id(a))  # id值相同

id值相同

__ new init__ 相配合才是python中真正的类构造器

4. __ setattr __()

class Fun:
    def __init__(self):
        self.name = "Liu"
        self.age = 12
        self.male = True
        
    def __setattr__(self, key, value):
        print("*"*50)
        print("setting:{},  with:{}".format(key[], value))
        print("current __dict__ : {}".format(self.__dict__))
        # 属性注册
        self.__dict__[key] = value
fun = Fun()  
**************************************************
setting:name,  with:Liu
current __dict__ : {}
**************************************************
setting:age,  with:12
current __dict__ : {'name': 'Liu'}
**************************************************
setting:male,  with:True
current __dict__ : {'name': 'Liu', 'age': 12}

init()中三个属性赋值时,每次都会调用一次__setattr__()

获取和管理可以通过__setattr__()和__dict__配合进行

5. __ eq __()

常常想对一个类所实例化出来的两个对象进行判断这两个对象是否是完全相同的。一般情况下,我们认为如果同一个类实例化出来的两个对象的属性全都是一样的话,那么这两个对象是相同的。

class Item:
 def __init__(self, name, weight):
  self.name=name
  self.weight=weight
 
 def __eq__(self, other):
  # `__eq__` is an instance method, which also accepts
  # one other object as an argument.
  
  if type(other)==type(self) and other.name==self.name and other.weight==self.weight:
   return True
  else:
   return False# 返回False这一步也是需要写的哈,不然判断失败就没有返回值了

cat_1 = Item('Cat', 5)
cat_2 = Item('Cat', 5)

print(cat_1.__eq__(cat_2)) #  True
print(cat_1 == cat_2) # True

6. __ repr __()

就是该对象的 repr() 方法,输出的是该方法的返回值。

class Demo:
    def __init__(self):
        self.name = "zs"
        self.age = "18"
    def __repr__(self):
        return self.name + self.age 
demo = Demo()
print(demo)
# zs18

7. __ dir __()

dir() 函数,通过此函数可以某个对象拥有的所有的属性名和方法名,该函数会返回一个包含有所有属性名和方法名的有序列表。

class Demo:
    def __init__(self):
        pass
demo = Demo()
print(dir(demo))

输出该方法名称列表

['__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__']
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值