码迷,mamicode.com
首页 > 其他好文 > 详细

知识点:构造和析构方法 __new__ , __init__ , __del__

时间:2017-04-09 22:02:42      阅读:272      评论:0      收藏:0      [点我收藏+]

标签:log   ret   调用   修改   div   class   大写   创建对象   __del__   

 

1:__new__ 类创建对象的一个执行的方法,一般不需要重写这个函数。当继承的类是不可变,但是又想修改该对象。

基本语法  def __new__(cls ,[args,]])

  ####写一个将字母全部大写的类####

 

class Capstr(str):
    def __new__(cls , string):
        string = string.upper()
        return str.__new__(cls , string)

print(Capstr("marian"))

 

 

####写一个类,当参数是字符串的时候,返回每个字符串的ASSLL值综合#####

>>> print(Nint(123))
123
>>> print(Nint(1.5))
1
>>> print(Nint("A"))
65
>>> print(Nint("marian"))
632

class Nint(int):
    def __new__(cls , arg):
        if isinstance(arg , str):
            total=0
            for each in arg:
                
            total += ord(each)
            arg = total
        return int.__new__(cls , arg)    
        

 

 

 ####写一个类,实现摄氏度转为华氏度#####

 

class C2F(float):
    def __new__(cls , arg=0.0):
        return float.__new__(cls , arg * 1.8 + 32 )

print(C2F(32))

 

 

2:__init__ (self ,[args])   类的构造方法

3:__del__ 类的析构方法

class T():
    def __init__(self):
        print("我是__init__方法,我被调用了...")

    def __del__(self):
        print("我是__del__方法,我被调用了...")

 

 

>>> t1 = T()
我是__init__方法,我被调用了...
>>> t2 = t1
>>> del t1
>>> del t2  #当所有指向对象的变量都被删除时才能调用__del__方法
我是__del__方法,我被调用了...

 

知识点:构造和析构方法 __new__ , __init__ , __del__

标签:log   ret   调用   修改   div   class   大写   创建对象   __del__   

原文地址:http://www.cnblogs.com/marianyad/p/6686650.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!