Extra details of python - for long term - part.2
2023-06-26
2 min read
2023-06-26
9. python中的__init__.py
reference
在python工程中,当python在一个目录下检测到__init__.py
文件时,就会把它当成一个module。__init__.py
可以是空的,也可以有内容。
--未整理完
10. python中的getattr()方法
getattr
方法可以获取一个模块其中的方法和属性,包括class名、直接定义的方法以及属性。
代码示例:
#在example.py文件中
class magical_method():
def __init__(self,num1,num2,num3):
self.num1 = num1
self.num2 = num2
self.num3 = num3
def __contains__(self,tar):
if tar == self.num1 or tar == self.num2 or tar == self.num3:
return False
else:
return True
def name(self):
print('qwe')
def another_example():
print('asdasd')
ppp = 2
#在同目录下的test.py文件中
import example
attr = dir(example)
print(attr)
#输出
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'another_example', 'magical_method', 'ppp']
需要注意的几个点:一只会输出直接定义在模块中的类名、方法、属性(变量),如果属性/方法/类是在其他类/方法之下,那么不会遍历出来;二可以通过isinstance(attr, type)
方法判断是否是类、callable(func_name)
判断是否是函数(是否可以被调用)、hasattr(obj, attr)
用来判断属性是否在指定类中;三如果没有__name__ == "__main__"
,那么在dir的时候会执行该模块。