当前位置:
首页 > temp > python入门教程 >
-
python魔法函数
In [1]:
class Company(object):
def __init__(self, employee_list):
self.employee_list = employee_list
In [4]:
company = Company(['张三', '李四', '王五'])
print(company)
In [7]:
class Company(object):
def __init__(self, employee_list):
self.employee_list = employee_list
def __str__(self):
return str(self.employee_list)
In [8]:
company = Company(['张三', '李四', '王五'])
print(company)
In [17]:
class Company(object):
def __init__(self, name=None):
self.name = name
def __str__(self):
return '*****公司名称为:%s*****' % self.name
In [18]:
c = Company(name='腾讯')
print(c)
In [23]:
str(c)
Out[23]:
In [19]:
c
Out[19]:
In [20]:
class Company(object):
def __init__(self, name=None):
self.name = name
def __str__(self):
return '*****公司名称为:%s*****' % self.name
def __repr__(self):
return '#####公司名称为:%s#####' % self.name
In [22]:
c = Company(name='腾讯')
c
Out[22]:
In [24]:
class Company(object):
def __init__(self, name=None, employee_lst=None):
self.name = name
self.employee_lst = employee_lst
def __len__(self):
return len(self.employee_lst)
In [26]:
c = Company(name='腾讯', employee_lst=['张三', '李四', '王五'])
len(c)
Out[26]:
In [48]:
class Company(object):
def __init__(self):
self.company_info = {}
def __setitem__(self,key,value): # 令类实例化对象可以通过c[key] = value的方式赋值
self.company_info[key] = value
def __getitem__(self,key): # 令类实例化对象可以通过c[key]的方式取值
return self.company_info[key]
def __delitem__(self, key): # 令类实例化对象可以通过del c[key]的方式删除值
del self.company_info[key]
In [51]:
c = Company()
c['name'] = '腾讯'
c['type'] = 'IT'
print(c['name'])
del c['name']
print(c.company_info)
In [59]:
class Company(object):
def __setitem__(self,key,value):
setattr(self, key, value)
def __getitem__(self,key):
return getattr(self, key)
def __delitem__(self, key):
delattr(self, key)
In [60]:
c = Company()
c['name'] = '腾讯'
c['type'] = 'IT'
In [61]:
c['type']
Out[61]:
In [62]:
del c['type']
In [63]:
c['type']
In [67]:
class Company(object):
def __init__(self):
self.company_info = {}
def __contains__(self, key):
return key in self.company_info
In [69]:
c = Company()
c.company_info['name'] = '腾讯'
print('name' in c)
print('type' in c)
In [70]:
class Company(object):
def __setitem__(self,key,value):
setattr(self, key, value)
def __contains__(self, key):
return hasattr(self, key)
In [75]:
c = Company()
c['name'] = '腾讯'
print('name' in c)
print('type' in c)
In [99]:
from collections.abc import Iterable
from collections.abc import Iterator
In [81]:
isinstance(123, Iterable) # 整型不是可迭代对象
Out[81]:
In [101]:
isinstance('abc', Iterator) # 字符串不是迭代器
Out[101]:
In [102]:
isinstance('abc', Iterable) # 字符串是可迭代对象
Out[102]:
In [103]:
class Company():
def __iter__(self): # 自定义一个类,只要实现了__iter__方法,就是可迭代对象
pass
print('Company()是可迭代对象吗:',isinstance(Company(),Iterable))
print('Company()是迭代器吗:',isinstance(Company(),Iterator))
In [104]:
class Company():
def __iter__(self):
pass
def __next__(self): # 自定义一个类,同时实现了__iter__方法和__next__方法,就是迭代器
pass
print('Company()是可迭代对象吗:',isinstance(Company(),Iterable))
print('Company()是迭代器吗:',isinstance(Company(),Iterator))
In [94]:
class B():
def __init__(self, lst):
self.lst = lst
self.index = 0
def __iter__(self):
print('B.__iter__()方法被调用')
return self
def __next__(self):
try:
print('B.__next__()方法被调用')
value = self.lst[self.index]
self.index += 1
return value
except IndexError:
raise StopIteration()
In [98]:
b = B([1, 2, 3])
for i in b:
print(i)
In [88]:
class Company(object):
def __init__(self):
pass
def __call__(self, name):
self.name = name
print('__call__方法被调用,name:%s' % self.name)
In [89]:
c = Company()
c('腾讯')
In [90]:
class Company(object):
def __init__(self):
pass
def A():
pass
In [91]:
print('类Company是否有__call_方法:', hasattr(Company, '__call__'))
print('函数A是否有__call_方法:', hasattr(A, '__call__'))
In [92]:
class Company(object):
def __init__(self):
self.name = None
def func(self):
pass
In [93]:
c = Company()
print('c中是否存在属性name:', hasattr(c, 'name'))
print('c中是否存在属性func:', hasattr(c, 'func'))
print('name是函数吗:', hasattr(c.name, '__call__'))
print('func是函数吗:', hasattr(c.func, '__call__'))
In [3]:
import pymysql
class Dao(object):
def __init__(self, cursor_type=None):
self.conn = pymysql.connect( # 创建数据库连接
host='192.168.31.201', # 要连接的数据库所在主机ip
database='test',
user='root', # 数据库登录用户名
password='admin123456', # 登录用户密码
charset='utf8' # 编码,注意不能写成utf-8
)
self.cursor = None
if cursor_type:
self.cursor = self.conn.cursor(pymysql.cursors.DictCursor)
else:
self.cursor = self.conn.cursor()
def __enter__(self):
return self.cursor # 返回类实例本身
def __exit__(self, exc_type, exc_value, exc_trace):
self.conn.commit() # 提交事务
self.cursor.close() # 关闭游标
self.conn.close() # 关闭数据库连接
In [6]:
with Dao() as cursor:
cursor.execute("select * from employee;")
e = cursor.fetchall()
print(e)
In [13]:
class Company(object):
def __init__(self, name):
self.company_name = name
def fun(self):
print('fun方法被调用……')
def __getattr__(self, name):
print('__getattr__方法被调用')
raise AttributeError('哥们,你查找的属性"%s"不存在' % name)
In [14]:
c = Company('腾讯')
In [15]:
print(c.company_name)
print(c.fun)
In [16]:
c.abc
In [21]:
class Dict(dict):
def __init__(self, *args, **kwargs):
super(Dict, self).__init__(*args, **kwargs)
def __getattr__(self, key):
try:
return self[key]
except KeyError:
raise AttributeError(r"'Dict' object has no attribute '%s'" % key)
In [22]:
d = Dict({'name': '张三', 'age': '李四'})
d.name
Out[22]:
In [27]:
class Company(object):
def __init__(self, name):
self.company_name = name
def __setattr__(self, name, value):
print("__setattr__方法被调用")
# self.name = value # 第一种写法
# object.__setattr__(self, name, value) # 第二种写法
self.__dict__[name] = value # 第三种写法
In [29]:
c = Company('腾讯')
c.company_name = '阿里'
print(c.company_name)
In [30]:
class Dict(dict):
def __init__(self, *args, **kwargs):
super(Dict, self).__init__(*args, **kwargs)
def __getattr__(self, key):
try:
return self[key]
except KeyError:
raise AttributeError(r"'Dict' object has no attribute '%s'" % key)
def __setattr__(self, key, name):
self[key] = name
In [31]:
d = Dict()
d.name = '张三'
print(d.name)
In [32]:
class Company(object):
def __init__(self, name):
self.company_name = name
def __getattribute__(self, name):
print('__getattribute__方法被调用')
return object.__getattribute__(self, name)
# raise AttributeError('哥们,你查找的属性"%s"不存在' % name)
In [33]:
c = Company('腾讯')
c.company_name
Out[33]:
In [34]:
c.abc
In [37]:
class Company(object):
def __init__(self, name):
self.company_name = name
def fun(self):
print('fun方法被调用……')
In [38]:
c = Company('腾讯')
In [40]:
c.__dict__
Out[40]:
In [41]:
Company.__dict__
Out[41]:
In [44]:
dir(c)
Out[44]:
In [45]:
c.__dir__()
Out[45]:
出处:https://www.cnblogs.com/chenhuabin/p/13752770.html
最新更新
nodejs爬虫
Python正则表达式完全指南
爬取豆瓣Top250图书数据
shp 地图文件批量添加字段
爬虫小试牛刀(爬取学校通知公告)
【python基础】函数-初识函数
【python基础】函数-返回值
HTTP请求:requests模块基础使用必知必会
Python初学者友好丨详解参数传递类型
如何有效管理爬虫流量?
2个场景实例讲解GaussDB(DWS)基表统计信息估
常用的 SQL Server 关键字及其含义
动手分析SQL Server中的事务中使用的锁
openGauss内核分析:SQL by pass & 经典执行
一招教你如何高效批量导入与更新数据
天天写SQL,这些神奇的特性你知道吗?
openGauss内核分析:执行计划生成
[IM002]Navicat ODBC驱动器管理器 未发现数据
初入Sql Server 之 存储过程的简单使用
SQL Server -- 解决存储过程传入参数作为s
关于JS定时器的整理
JS中使用Promise.all控制所有的异步请求都完
js中字符串的方法
import-local执行流程与node模块路径解析流程
检测数据类型的四种方法
js中数组的方法,32种方法
前端操作方法
数据类型
window.localStorage.setItem 和 localStorage.setIte
如何完美解决前端数字计算精度丢失与数