您的位置:首页 > 编程语言 > Python开发

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类似于函数的集合,越简洁越好,多用函数
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息