First, the functions and methods
1. The difference between the functions and methods
Function: all dominant mass participation, manual transmission parameters, regardless of the subject
Methods: The existence of hidden mass participation, and related objects
1.1 can be judged by the function name
len()就是函数
str.count()就是方法
def func():
pass
class A:
def func(self):
print(func)
obj = A()
print(obj.func())
By determining the types module 2.2
from types import functionType
from types import MethodType
print(isinstance(func,FunctionType))
print(isinstance(func,MethodType))
- The class name is a function call func
- The object is to call a method func
2.3 Research for static methods
print(isinstance(A.f, FunctionType)) #指的是函数类型
print(isinstance(A.f, MethodType)) #类方法
Second, reflection
What is the use
There are times when you knew a variable string data type the name you want to call it, but less than a tune, you can use reflection
Reflection method
A string to operate the object by
getattr 获取一个属性或者方法
getattr(obj,'name1',None) #前面是类名,后面是字符串形式的属性或方法
hasattr 判断属性或方法是否存在
hasattr(obj,'name')
setattr 设置新的属性
setattr(obj,'hobby', '玩')
hasattr 删除属性
hasattr(obj, 'func')
Reflecting object instantiation
Instantiating the object in front of the name, followed by a property of the object instance in the form of a string
class Foo:
f = '类的静态变量'
def __init__(self, name, age):
self.name = name
self.age = age
def say_hi(self):
print(f'hi,{self.name}')
obj = Foo('egon', 73)
# 检测是否含有某属性 name
print(hasattr(obj, 'name'))
print(hasattr(obj, 'say_hi'))
# 获取属性
n = getattr(obj, 'name') # 等同于 obj.name
print(n)
func = getattr(obj, 'say_hi')
func()
# print(getattr(obj, 'aaaaaaaa', '不存在啊')) # 报错
# 设置属性
setattr(obj, 'sb', True) # 等同于 obj.sb = True
setattr(obj, 'show_name', lambda self: self.name + 'sb')
print(obj.__dict__)
print(obj.show_name(obj))
# 删除属性
delattr(obj, 'age') # 等同于 del obj.age
delattr(obj, 'show_name')
# delattr(obj, 'show_name111') # 不存在,则报错
print(obj.__dict__)
Reflection of the class
In front of the class name, property or method followed by a string of class
class Foo(object):
staticField = "old boy"
def __init__(self):
self.name = 'wupeiqi'
def func(self):
return 'func'
@staticmethod
def bar():
return 'bar'
print(getattr(Foo, 'staticField')) # 前面是类名,后面是类的属性或方法
print(getattr(Foo, 'func'))
print(getattr(Foo, 'bar'))
Reflected current module
import sys
def s1():
print('s1')
def s2():
print('s2')
this_module = sys.modules[__name__] # 比较推荐#sys.modules 获得到的是 当前文件的所有属性及方法,返回是一个字典
# 等同于 this.module = sys.modules["__main__"]
hasattr(this_module, 's1')
getattr(this_module, 's2')()
Reflecting other modules
"""
程序目录:
module_test.py
index.py
"""
# module_test.py 中的代码
def test():
print('from the test')
# index.py 中的代码
import module_test as obj
# obj.test()
print(hasattr(obj, 'test'))
getattr(obj, 'test')()
class A:
static_field = '静态属性'
def __init__(self, name, age):
self.name = name
self.age = age
def func(self):
print('in A func')
obj = A('MC骚Q', 18)
print(obj.name)
#
print(hasattr(obj,'name')) # ***
print(getattr(obj,'name1',None)) ***
setattr(obj,'hobby', '玩') *
print(getattr(obj,'hobby'))
print(obj.hobby)
delattr(obj,'name') *
print(hasattr(obj,'name'))
if hasattr(obj, 'static_field'):
print(getattr(obj,'static_field'))
if hasattr(obj, 'func'):
# print(getattr(obj,'func'))
getattr(obj,'func')()
Third, the method of bis
__len__
use
Number of attributes can be acquired class, such as __init__
the
format
def __len(self):
print('触发__len__方法')
return 10
Trigger method
len(obj)
The reason why an object can use len () function, the root cause is the object class you have from the input __len__
method, the method is actually executed ** len when the class is not __len__ this method, using len () will throw an error **
__hash__
use
Hash
Trigger method
print(hash(obj))
__str__
method
use
Print output
Trigger method
print(obj)
__repr__
method
use
The same __str__
as when there is simultaneous with str, str higher priority
Trigger method
print(此对象是%r那就先执行repr的方法)
__call__
method
Trigger method
obj() #对象加括号触发就会触发类里面的__call__方法
__eq__
method
use
When you are in a class of two objects compare operation, it will trigger __eq__
method
__del
method
What is the use
Object reference for zero time, destructors, automatically deleted
Removed from memory, the garbage collection mechanism ♻️
Call the method
l2 = [1,2,3]
dic = {1:22, 2:33}
del l2
del dic #主动删除
__new__
(*****************)
What use
- Constructs an object out (performed automatically
__init__
when the file is__new__
in the dry this thing children) - Creating build and returns a new space
class A(object):
def __init__(self):
print('in __init__')
def __new__(cls, *args, **kwargs):
print('in __new__')
object1 = object.__new__(cls)
return object1
obj = A()
# 输出结果
in __new__
in __init__
Singleton
Singleton Pattern Singleton pattern is a design pattern, a class intelligent instantiate an object, no matter how many times you instantiate memory are only one object, the purpose is to save space
Interview almost always let you hand a singleton
class A:
__instance = None
def __new__(cls, *args, **kwargs):
if not cls.__instance:
object1 = object.__new__(cls)
cls.__instance = object1
return cls.__instance
obj = A()
obj1 = A()
obj2 = A()
obj3 = A()
print(obj, obj1, obj2, obj3)
__item__
method
use
Operate on an object like a dictionary
__getitem__、__setitem__、__delitem__、
class Foo:
def __init__(self, name):
self.name = name
def __getitem__(self, item):
print(item)
print('get时 执行我')
def __setitem__(self, key, value):
self.name = value
print('set时执行我')
def __delitem__(self, key):
print(f'del obj{[key]}时,我执行')
obj = Foo('御姐')
# obj.__dict__
# obj['name']
# obj['name'] = '萝莉'
# print(obj.name)
del obj['name']
class Foo:
def __init__(self, name, key, value):
self.name = name
self.dict = {}
self.dict[key] = value
def __getitem__(self, key):
print("1313", self.dict[key])
# return self.dict[key]
def __setitem__(self, key, value):
self.__dict__[key] = value
print(key, "创建新的键值对")
def __delitem__(self, key):
print('del obj[', key, ']时,我执行')
self.__dict__.pop(key)
def __delattr__(self, item):
print('del obj.', item, '时,我执行')
self.__dict__.pop(item)
f1 = Foo("sb", "A", "1")
f1["A"] # 会去执行 __getitem__ 方法
f1['age'] = 18 # 会去执行 __setitem__ 方法
f1['age'] = 112 # 修改也会去执行 __setitem__ 方法
f1['age1'] = 250 # 修改也会去执行 __setitem__ 方法
del f1.age1 # 会去执行 __delattr__ 方法
del f1['age'] # 会去执行 __delitem__ 方法
f1['name'] = 'alex' # 会去执行 __setitem__ 方法
print(f1.__dict__)
Authentication using the class method ***
class Auth:
function_list = [('login','请登录'),('register','请注册'),('exit_q','退出')]
def login(self):
print('欢迎登录')
def register(self):
print('欢迎注册')
def exit_q(self):
print('退出程序')
exit()
while 1:
obj = Auth()
for num,option in enumerate(obj.function_list,1):
print(num,option[1])
try:
choice_num = input('请输入选择: ').strip()
if hasattr(obj,obj.function_list[int(choice_num)-1][0]):
getattr(obj,obj.function_list[int(choice_num)-1][0])()
except IndexError:
print('请输入超过范围')
except ValueError:
print('请输入数字')