python如何调用类中的方法
python调用类中的方法:
调用同一个类中的方法
首先类中的方法在定义的时候需要先加参数self,例如:
defSaveData(self,ip):
print(ip)
如果无self参数则不能在同一个类中调用(之前一直在这里犯错,警醒之)
无self参数的情况下是可以在另一个文件中调用的,但是不推荐,规范写法,每个函数第一个参数都应为self(其他名字也可以,
但是我们大家约定俗称均写为self),下面是实例:
classA():
if__name__=="__main__":
print('入口')
self.Bfunc("192.168.1.1")
def__init__(self):
#初始化;类似于C#中构造函数
defAfunc(self,ip):
print(ip)
defBfunc(self,ip):
self.Afunc(ip)
调用另一个类中的方法
A.py和B.py在同一个文件夹下面,可以通过from文件名import*或者importA来互相调用。
fromAimportA
a=A()
a.Afunc("123456")
a.Bfunc("123456")
不同文件夹下的py文件
A.py文件的文件路径:E:\PythonProject\winycg
B.py文件:
importsys
sys.path.append(r'E:\PythonProject\winycg')
'''pythonimport模块时,是在sys.path里按顺序查找的。
sys.path是一个列表,里面以字符串的形式存储了许多路径。
使用A.py文件中的函数需要先将他的文件路径放到sys.path中'''
importA
a=A.A(2,3)
以上内容为大家介绍了python培训之如何调用类中的方法,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注IT培训机构:千锋教育。

相关推荐HOT
更多>>
python函数标注是什么
python函数标注是什么在参数的使用方法中,还有一种解包的情况是需要我们掌握的。比如,将列表或者字典的值转换为函数的参数,就需要用到参数解...详情>>
2023-11-14 14:13:35
python正负索引的使用
python正负索引的使用本文教程操作环境:windows7系统、Python3.9.1,DELLG3电脑。1、说明使用正索引(从左至右)、负索引(从右至左)访问元素,时...详情>>
2023-11-14 13:45:04
python垃圾回收的机制过程
python垃圾回收的机制过程本文教程操作环境:windows7系统、Python3.9.1,DELLG3电脑。1、步骤(1)收集所有容器对象(list,dict,tuple,customClas...详情>>
2023-11-14 13:05:15
pythontry语句的执行原理
pythontry语句的执行原理1、原理分析(1)执行try子句(try和except关键字之间的多行语句)。(2)如果没有异常发生,则跳过except子句并完成try语句...详情>>
2023-11-14 09:37:35热门推荐
技术干货






