python---面向对象,class参数、__init__方法、与函数区别
2017-11-19 12:26
661 查看
python—面向对象,class简介
进阶 面向对象第一节 初识class 1.如何去定义一个最基本的class 2.class最基本的子元素 3.class传参 4.__init__方法 5.class和函数的区别(class类似于函数的集合,越简洁越好,多用函数) 1)class的实例 >>> class test(object): ... pass ... >>> d = test()#d是类test的一个实例 >>> print d <__main__.test object at 0xb748b58c> >>> 2)class的方法 class test(object): #get被称之为test对象的方法,属于变量本身的外部不可调用 def get(self): return "hahhaha" pass t = test() print t.get()#调用 #代码运行 >>> class test(object): ... def get(self): ... return "hahah" ... pass ... >>> t = test()#t是类test的一个实例 >>> print t.get()#调用get方法 hahah >>> >>> def getfun():#函数功能定义 ... return "xixixixi" ... >>> print getfun()#使用函数调用 xixixixi >>> 如何去使用对象内置的方法 1.实例化这个class (test) t = test() 2.使用 class.method()的方式去调用 class 的内置方法 注意: 1).当定义一个class的内置方法method时,method的参数的第一个永远是self。 >>> class test(object): ... def get(self,a): ... return a ... pass ... >>> t = test()t是类test的一个实例 >>> new_var = 66 >>> print t.get(new_var)#调用get方法 66 >>> >>> def getfunc(b):#函数功能 ... return b ... >>> print getfunc(new_var) 66 >>> class内置方式get():不使用self时: >>> class test(object): ... def get(a): ... return a ... pass ... >>> t = test() >>> new_var = 77 >>> print t.get(new_var) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: get() takes exactly 1 argument (2 given) >>> class的内置__init__的方法使用: 1)返回数字 >>> class test(object): ... def __init__(self,var1): ... pass ... def get(self,a): ... return a ... pass ... >>> t = test(88) >>> new_var = 88 >>> print t.get(new_var) 88 >>> print t.get() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: get() takes exactly 2 arguments (1 given) >>> print t.get(9999) 9999 >>> 2)返回字符串(init方式self定义后可以全局调用,使用self定义后可以放到class中的任意函数中调用) >>> class test(object): ... def __init__(self,var1): ... self.var1 = var1#定义后可以全局调用,使用self定义后可以放到class中的任意函数中调用 ... def get(self,a=None): ... return self.var1 ... pass ... >>> t = test("hello world!!! good day!!") >>> print t.get() hello world!!! good day!! >>> 内置init的方法比如: 男女恋爱过程: 首先有love对象class,引入男孩与女孩名字 new_love = love("boy_name","girl_name") 然后实例化love对象后,他们两生怎样的孩子,有怎样父母、有怎样的房子 print new_love.get_children() print new_love.get_father() print new_love.get_house() 当中也可以为男孩和女孩也可以定义class对象 new_love = love(boy_object,girl_object) 5.class和函数的区别: class类似于函数的集合,越简洁越好,多用函数
相关文章推荐
- python @classmethod 和 @staticmethod区别,以及类中方法参数cls和self的区别
- python 函数参数 调用的常见方法
- Python函数参数类型*、**的区别
- python通过装饰器检查函数参数数据类型的方法
- python函数参数前面单星号(*)和双星号(**)的区别
- python中函数参数传递的几种方法
- python进阶教程之函数参数的多种传递方法
- python中staticmethod classmethod及普通函数的区别
- caffe的python接口学习(12):查看属性、方法以及函数参数
- 关于Python的属性、参数、方法的解释、区别
- Python3基础 重写__init__方法 在类的实例化的时候传入参数
- python中函数参数传递的几种方法
- 浅谈Python类里的__init__方法函数,Python类的构造函数
- Python中__new__与__init__方法的区别详解
- python中函数参数传递的几种方法
- Python函数小结(1)--参数类型(*, ** 的区别), 闭包
- 浅谈Python类里的__init__方法函数,Python类的构造函数
- OC中类的函数参数问题,以及方法与函数的区别。
- Python中的__init__方法与__new__方法的区别
- python进阶教程之函数参数的多种传递方法