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

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类似于函数的集合,越简洁越好,多用函数
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

徐为波

看着给就好了,学习写作有点累!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值