python---面向对象,class参数、__init__方法、与函数区别

来源:互联网 发布:大数据存储解决方案 编辑:程序博客网 时间:2024/06/03 23:05

python—面向对象,class简介

进阶 面向对象第一节 初识class1.如何去定义一个最基本的class2.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"    passt = 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类似于函数的集合,越简洁越好,多用函数
原创粉丝点击