Python 类的使用一

简介:

一,self含义


1
2
3
4
5
6
7
# -*- coding: utf-8 -*-
class  person:
     def  one( self ,name,age):
         print  "you name is %s and you age is %s."  %  (name, age)
 
=  person()  #绑定实例
p.one( "du" , 22 )


执行结果:

1
you name  is  du  and  you age  is  22.


其实self可以不必写成self,但是必须要有一个参数如下图

wKiom1l0qE6h4ZLDAAA_ZXxRC5M801.png-wh_50


详细了解可以参考博客:http://www.cnblogs.com/jessonluo/p/4717140.html





二,__init__初始化。

1
2
3
4
5
6
7
8
9
# -*- coding: utf-8 -*-
class  person:
     def  __init__( self ,sex):
         self .sex  =  sex
     def  one( self ,name,age):
         print  "you name is %s and you age is %s and sex is %s"  %  (name, age,  self .sex)
 
=  person( "boy" #绑定实例
p.one( "du" , 22 )


执行结果:

1
you name  is  du  and  you age  is  22  and  sex  is  boy


其实就相当于变量sex在类里。比函数大一级别。如下面的程序,和上面的执行结果是一样的。


1
2
3
4
5
6
7
8
9
10
11
# -*- coding: utf-8 -*-
class  person:
     sex  =  "boy"
     def  __init__( self ,sex):
         #self.sex = sex
         pass
     def  one( self ,name,age):
         print  "you name is %s and you age is %s and sex is %s"  %  (name, age,  self .sex)
 
=  person( "boy" #绑定实例
p.one( "du" , 22 )




wKiom1l0rM7wxVsHAAQF1aT1ixQ739.png



本文转自 天道酬勤VIP 51CTO博客,原文链接:http://blog.51cto.com/tdcqvip/1950270

相关文章
|
3天前
|
前端开发 Python
Python编程的面向对象(二)—类的多态
Python编程的面向对象(二)—类的多态
12 7
|
2天前
|
IDE Java 开发工具
Python类与面向对象
Python类与面向对象
|
6天前
|
关系型数据库 MySQL Python
mysql之python客户端封装类
mysql之python客户端封装类
|
7天前
|
Python
python 类中的内置方法
python 类中的内置方法
|
5天前
|
Python
Python类中属性和方法区分3-8
Python类中属性和方法区分3-8
|
2月前
|
供应链 数据挖掘 Serverless
【python】美妆类商品跨境电商数据分析(源码+课程论文+数据集)【独一无二】
【python】美妆类商品跨境电商数据分析(源码+课程论文+数据集)【独一无二】
【python】美妆类商品跨境电商数据分析(源码+课程论文+数据集)【独一无二】
|
2月前
|
Python
12类常用的Python函数
12类常用的Python函数
|
2月前
|
存储 程序员 Python
Python类的定义_类和对象的关系_对象的内存模型
通过类的定义来创建对象,我们可以应用面向对象编程(OOP)的原则,例如封装、继承和多态,这些原则帮助程序员构建可复用的代码和模块化的系统。Python语言支持这样的OOP特性,使其成为强大而灵活的编程语言,适用于各种软件开发项目。
17 1
|
2月前
|
存储 程序员 C++
python类及其方法
python类及其方法
|
2月前
|
C++ Python
python类方法中使用:修饰符@staticmethod和@classmethod的作用与区别,还有装饰器@property的使用
python类方法中使用:修饰符@staticmethod和@classmethod的作用与区别,还有装饰器@property的使用
16 1