Python 魔術方法

2021-09-02 18:57:34 字數 802 閱讀 4522

#!/usr/bin/env python

# -*- coding: utf-8 -*-

# author:ray time:2018/12/6

# 魔術方法例項

#__init__()-->建構函式,在生成物件時呼叫,用來初始化值

# __del__()-->析構函式,釋放物件時使用:比如編輯檔案,把關閉檔案的操作寫在此方法中,程式結束時就會關閉軟體

#__str__()-->使用print(物件)或者str(物件)的時候觸發,用來return乙個字串

class file:

def __init__(self, name):

self.name = name

print("open file ", self.name)

def __del__(self):

print("close file", self.name)

a = file('a.txt')

class stu:

name = 'zhangsan'

age = 20

def __str__(self):

return "name:%s;age%d" % (self.name, self.age)

s = stu()

print(s)

#輸出#open file a.txt

#name:zhangsan;age20

#close file a.txt

#process finished with exit code 0

python 魔術方法

魔術方法 呼叫方式 解釋 new cls instance myclass arg1,arg2 new 在建立例項的時候被呼叫 init self instance myclass arg1,arg2 init 在建立例項的時候被呼叫 cmp self,other self other,self o...

Python魔術方法

參考文章 python 魔術方法指南 魔術方法,顧名思義是一種可以給物件 類 增加魔法的特殊方法,它們的表示方法一般是用雙下劃線包圍 如 init from os.path import join class fileobject 給檔案物件進行包裝從而確認在刪除時檔案流關閉 def init se...

Python 魔術方法

與運算子無關 類別方法名 數值轉換 abs bool complex int float hash index 模擬集合 len getitem setitem delitem contains 迭代列舉 iter reversed next 可呼叫模型 call 上下文管理 enter exit ...