python(类和对象相关知识)
类与对象的关系:对象都是由类产生的。
实例化:由类生产对象的过程。
类的属性分为数据属性(变量)和函数属性(函数,也叫方法)。
类和对象都使用点来访问。
一个简单的类
# -*- coding: utf-8 -*-
class car:
‘这是一个车的类‘ #类的说明
wheel=‘橡胶‘
Engine=‘发动机‘
def transport(self):
print(‘---拉货---‘)
def manned(self):
print(‘---载人---‘)
print(car.__dict__) #查看类的属性字典
print(car.wheel)
car.transport(‘1‘) 查看类的属性
# -*- coding: utf-8 -*-
class car:
‘这是一个车的类‘ #类的说明
wheel=‘橡胶‘
Engine=‘发动机‘
def transport(self):
print(‘---拉货---‘)
def manned(self):
print(‘---载人---‘)
print(car.__name__) #查看类名
print(car.__doc__) #查看类的说明文档
print(car.__base__) #查看类的祖先
print(car.__bases__) #查看类的祖先(元组形式)
print(car.__module__) #查看类所在的模块类的实例化与方法调用
# -*- coding: utf-8 -*-
class car:
‘这是一个车的类‘ #类的说明
wheel=‘橡胶‘
Engine=‘发动机‘
def __init__(self,License,brand,price): #初始化必须这么些(__init__),自动return
#产生self字典
self.Licenses=License
self.brands=brand
self.prices=price
def transport(self):
print(‘---拉货---‘)
def manned(self):
print(‘---载人---‘)
car1=car(‘123456‘,‘大众‘,‘100000‘)
print(car1.__dict__)
#两种方法查看类的属性
print(car1.__dict__[‘Licenses‘])
print(car1.Licenses)
car2=car(‘345678‘,‘奔驰‘,‘200000‘)
print(car1.__dict__)
#调用方法
car2.transport()带参方法的创建与调用
# -*- coding: utf-8 -*-
class car:
‘这是一个车的类‘ #类的说明
wheel=‘橡胶‘
Engine=‘发动机‘
def __init__(self,License,brand,price): #初始化必须这么些(__init__),自动return
#产生self字典
self.Licenses=License
self.brands=brand
self.prices=price
def transport(self):
print(‘---拉货---‘)
def manned(self):
print(‘---载人---‘)
#带参方法
def colors(self,color):
print(‘---%s的颜色是%s---‘%(self.Licenses,color))
car1=car(‘123456‘,‘大众‘,‘100000‘)
car1.colors(‘白色‘)类属性的增,删,改,查
# -*- coding: utf-8 -*-
class car:
‘这是一个车的类‘ #类的说明
wheel=‘橡胶‘
Engine=‘发动机‘
def __init__(self,License,brand,price): #初始化必须这么些(__init__),自动return
#产生self字典
self.Licenses=License
self.brands=brand
self.prices=price
def transport(self):
print(‘---拉货---‘)
def manned(self):
print(‘---载人---‘)
#带参方法
def colors(self,color):
print(‘---%s的颜色是%s---‘%(self.Licenses,color))
#查看类的属性
print(car.wheel)
#修改类的属性
car.wheel=‘自然橡胶‘
print(car.wheel)
#增加类的属性
car.year=‘15‘
print(car.year)
#删除类的属性
car.seat=‘4‘
print(car.__dict__)
del car.seat
print(car.__dict__)
#类的方方法的增删改查方法与属性一样
#例子(增)
def speeds(self,speed):
print(‘---%s的最高时速是%s---‘ % (self.Licenses,speed))
car.add_speeds=speeds
car1=car(‘123456‘,‘大众‘,‘100000‘)
car1.add_speeds(‘150km/h‘) 相关推荐
class Singleton: def __new__: # 关键在于这,每一次实例化的时候,我们都只会返回这同一个instance对象 if not hasattr: cls.instance =
lhxxhl 2020-05-16
钟鼎 2020-06-05
致终将努力的我们 2020-04-18
小菜鸟的代码世界 2020-04-15
VanTYS 2020-04-09
yunfenglee 2020-02-18
坚持是一种品质 2019-11-06
yuan00yu 2019-06-27
MarkArch 2019-06-25
xhqiang 2019-06-25
yixiaoqi00 2010-04-07
pdw00 2019-06-21
Sincelily 2012-12-12
麋鹿麋鹿迷了路 2011-05-21
littlecushion000 2014-08-04
laj0 2018-10-30
xiatianbzh 2018-08-30
BlueLzy的个人 2018-04-16
woxiaozhi 2018-03-16