一、定义类、子类、类的实例化、子类的实例化、继承、实例属性和实例方法

示例:

class Fruit():
'''
定义一个水果类,包含水果的一些属性和一些方法。
'''
def __init__(self,name,color,shape,taste):
self.name = name
self.color = color
self.shape = shape
self.taste = taste
print(self.name+"的小时候是这样的,它的颜色是:"+self.color+",它的形状是:"+self.shape+",它的味道是:"+self.taste)
def colorChange(self,new_color):
self.color = new_color
print(self.name + "的颜色变成了:"+self.color)
def sizeChange(self,new_size):
self.shape = new_size
print(self.name + '的大小变成了:'+self.shape)
def tasteChange(self,new_taste):
self.taste = new_taste
print(self.name + '的味道变成了:'+self.taste)
def growUp(self):
print("慢慢的它长大了...") class waterFruit(Fruit):
'''
定义一个水分多的水果类,包含多水分的属性和一些方法。
'''
def __init__(self,name,color,shape,taste,water_pencent):
# Fruit.__init__(self,name,color,shape,taste)
self.name = name
self.color = color
self.shape = shape
self.taste = taste
self.water_pencent = water_pencent
print(self.name+"的小时候是这样的,它的颜色是:"+self.color+",它的形状是:"+self.shape+",它的味道是:"+self.taste+",它的水分是:"+self.water_pencent)
def waterChange(self,new_water):
self.water_pencent = new_water
print(self.name + "的水分变成了:" + self.water_pencent)
banana = Fruit('香蕉','绿色','长条形','微甜')
banana.growUp()
banana.colorChange('黄色')
banana.sizeChange('椭圆形')
banana.tasteChange('很甜')
watermelon = waterFruit('西瓜','绿色','圆形','甜的','90%')
watermelon.growUp()
watermelon.waterChange("95%")
watermelon.tasteChange("超级甜")

二、类属性

1、类的数据属性:它是静态的类属性,直接绑定在类上而不是某个实例上,在使用时通过类+"."操作符+属性来调用。如下例:

>>> class foo():
foo = 100
>>>
>>> print(foo.foo)
100
>>> foo.foo += 1
>>> print(foo.foo)
101
>>>

2、方法(也是类的属性):必须通过实例去调用,类不能直接调用。

>>> class foo():
foo = 100
def doNothing(self):
print('Do nothing!')
>>>
# 必须先实例化对象:
>>> fooAction = foo()
>>> fooAction.doNothing()
Do nothing!
# 直接用类调用方法时报错:
>>> foo.doNothing()
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
foo.doNothing()
TypeError: doNothing() missing 1 required positional argument: 'self'

3、查看类的属性:

# 1:通过内建函数dir()查看类的内部属性,返回的是一个属性列表
>>> dir(foo)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'doNothing', 'foo']
# 2:通过类的__dict__属性查看,返回的是一个字典,key是属性名,value是具体的值。
>>> foo.__dict__
mappingproxy({'foo': 100, 'doNothing': <function foo.doNothing at 0x0000029E039C7F28>, '__weakref__': <attribute '__weakref__' of 'foo' objects>, '__dict__': <attribute '__dict__' of 'foo' objects>, '__doc__': None, '__module__': '__main__'})
>>> print(foo.__dict__)
{'foo': 100, 'doNothing': <function foo.doNothing at 0x0000029E039C7F28>, '__weakref__': <attribute '__weakref__' of 'foo' objects>, '__dict__': <attribute '__dict__' of 'foo' objects>, '__doc__': None, '__module__': '__main__'}

4、一些类的特殊属性

# 类的名字:
>>> print(foo.__name__)
foo
# 类说明
>>> foo.__doc__
>>> print(foo.__doc__)
None
>>>
>>> class fooo(foo):
pass
# 类的所有父类构成的元组
>>> print(foo.__bases__)
(<class 'object'>,)
>>> print(fooo.__bases__)
(<class '__main__.foo'>,)
>>>
# 类属性的字典查看方法
>>> print(foo.__dict__)
{'foo': 100, 'doNothing': <function foo.doNothing at 0x0000029E039C7F28>, '__weakref__': <attribute '__weakref__' of 'foo' objects>, '__dict__': <attribute '__dict__' of 'foo' objects>, '__doc__': None, '__module__': '__main__'}
# 定义类foo所在的模块:
>>> print(foo.__module__)
__main__
>>>
# 实例foo1所对应的类:
>>> print(foo1.__class__)
<class '__main__.foo'>
>>>

初始Python类的更多相关文章

  1. python类的定义和使用

    python中类的声明使用关键词class,可以提供一个可选的父类或者说基类,如果没有合适的基类,那就用object作为基类. 定义格式: class 类名(object): "类的说明文档 ...

  2. python类:magic魔术方法

    http://blog.csdn.net/pipisorry/article/details/50708812 魔术方法是面向对象Python语言中的一切.它们是你可以自定义并添加"魔法&q ...

  3. python 类编程相关内容(更新)

    python作为面向对象的编程语言,类和对象相关的编程当然是少不了的! python类: class 类名 : 变量名 [ = 初始值 ] …… def 函数名 ( self [ , 其余参数列表 ] ...

  4. (转)python类:magic魔术方法

    原文:https://blog.csdn.net/pipisorry/article/details/50708812 版权声明:本文为博主皮皮http://blog.csdn.net/pipisor ...

  5. Python类中super()和__init__()的关系

    Python类中super()和__init__()的关系 1.单继承时super()和__init__()实现的功能是类似的 class Base(object): def __init__(sel ...

  6. python基础之初始python

    初始python之基础一 一.Python 介绍 1.python的创始人为吉多·范罗苏姆(Guido van Rossum).1989年的圣诞节期间,吉多·范罗苏姆为了在阿姆斯特丹打发时间,决心开发 ...

  7. LightMysql:为方便操作MySQL而封装的Python类

    原文链接:http://www.danfengcao.info/python/2015/12/26/lightweight-python-mysql-class.html mysqldb是Python ...

  8. python 类属性与方法

    Python 类属性与方法 标签(空格分隔): Python Python的访问限制 Python支持面向对象,其对属性的权限控制通过属性名来实现,如果一个属性有双下划线开头(__),该属性就无法被外 ...

  9. python 类以及单例模式

    python 也有面向对象的思想,则一切皆对象 python 中定义一个类: class student: count = 0         books = [] def __init__(self ...

随机推荐

  1. 【Django】Django 文件下载最佳实践

    代码: from django.http import StreamingHttpResponse def big_file_download(request): # do something... ...

  2. CentOS6.5以runlevel 3开机时自动连接某无线设置示例

    [参考]http://blog.csdn.net/simeone18/article/details/8580592 [方法一] 假设无线网卡代号为wlan0,无线AP的essid为:TheWiFi, ...

  3. python模拟浏览器保存Cookie进行会话

    #! /usr/bin/env python # -*-coding:utf- -*- import urllib import urllib2 import cookielib class NetR ...

  4. 63.如何对单链表进行快排?和数组快排的分析与对比[quicksort of array and linked list]

    [本文链接] http://www.cnblogs.com/hellogiser/p/quick-sort-of-array-and-linked-list.html [题目] 单链表的特点是:单向. ...

  5. Android 和iOS 创建本地通知

    1 Android 中的发送本地通知的逻辑如下 先实例化Notification.Builder,再用builder创建出具体的Notification,创建时要指定好启动用的PendingInten ...

  6. BestCoder13 1001.Beautiful Palindrome Number(hdu 5062) 解题报告

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5062 题目意思:给出 N,找出 1 - 10^N 中满足 Beautiful Palindrome N ...

  7. codeforces 474D.Flowers 解题报告

    题目链接:http://codeforces.com/problemset/problem/474/D 题目意思:Marmot 吃两种类型的花(实在难以置信呀--):red 或者 white,如果要吃 ...

  8. HDU2067卡特兰数

    小兔的棋盘 Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Submi ...

  9. Light OJ 1296 - Again Stone Game (博弈sg函数递推)

    F - Again Stone Game Time Limit:2000MS     Memory Limit:32768KB     64bit IO Format:%lld & %llu ...

  10. Ubuntu 更新源

    1.首先备份Ubuntu12.04源列表 sudo cp /etc/apt/sources.list /etc/apt/sources.list.backup (备份下当前的源列表) 2.修改更新源 ...