#!/usr/bin/python
# -*- coding: utf-8 -*-
#Author: zhaosj
###Python 面向对象###
#Python作为一个面向对象的语言.
#定义类
#类是用来描述具有相同属性和方法的对象集合.
#eg.:通过Python定义自行车的类
class Bike:
compose = ['frame','wheel','pedal']
#类中的变量compose称为类的变量,专业术语为类的属性.
my_bike = Bike()
you_bike = Bike()
print(my_bike.compose)
print(you_bike.compose)
class Bike:
compose = ['frame','wheel','pedal']
my_bike = Bike()
my_bike.other = 'basket'
print(my_bike.other) #实例属性
#通过给类的实例属性进行赋值,也就是实例属性.compose属性属于所有的的该款自行车,而other属性只属于my_bike这个类的实例.
# #实例方法# #
字符串format()方法,就是函数.方法是对实例进行使用的,所以又叫实例方法.
class Bike:
compose = ['frame','wheel','pedal']
def use(self):
print('you are riding')
my_bike = Bike()
my_bike.use()
#执行结果:
#这里的《--self--》参数就是实例本身.
和函数一样,实例方法也是可以有参数的
class Bike:
compose = ['frame','wheel','pedal']
def use(self,time):
print('you are rid {}m'.format(time*1000))
my_bike = Bike()
my_bike.use(10)
#执行结果:
Python中的类有一些"魔法方法",_init_()方法就是其中之一,在我们创建实例的时候,不需要引用该方法也会被自动执行.
class Bike: def __init__(self): self.other = 'basket' def use(self,time): print('you are rid {}m'.format(time*100)) my_bike = Bike() print(my_bike.other)