0
点赞
收藏
分享

微信扫一扫

python的class类、模块和包

python的class类

#定义一个class
class test(object):

#self为默认参数,代表class的对象本身
def __init__(self, var): #构造函数
self.var = var #self中定义的成员变量可在被class中的其他函数引用

a = 1 #a被称为属性

def get(self, a=None): #get被称为test对象的方法
return self.var, a

def __del__(self): #析构函数
del self.var


"""
使用对象内置的方法
1.实例化这个class (test) t = test()
2.使用class.method()的方式去调用class的内置方法



注意:当定义一个class的内置方法method时,method的参数的第一个永远是self
"""

#类的调用
t = test("hello world") #t是类test的一个实例
name, var = t.get(5)
print(name, var)



#类的继承
class father(object):

def __init__(self, name):
self.name = name

class son(father): #继承father

def get_name(self):
return self.name

t = son("hello world")
print(t.get_name())

python的模块和包

#包和模块     很像C语言中自己写的一个.h和.c文件

#模块
#定义一个文件myfunc.py
def func():
return hello world

#在主文件里
import myfunc
print(myfunc.func())



#包 假设包的名字为mybocket 在包里面先创建一个__init__.py文件
# 然后在包里面创建上面的myfunc.py文件
import mybocket.myfunc #引入包中的模块
print(mybocket.myfunc.func())


举报

相关推荐

0 条评论