一、概念
概念:
向对象最重要的概念就是类(class)和实例(instance),
必须牢记类是抽象的模板,比如student类,
而实例是根据类创造出来的一个个具体的“对象”,
每个对象都拥有相同的方法,但各自的数据可能不同
'''
设计类
类名:见名知意,首字母大写,其他遵循驼峰命名法
属性:见名知意,其他遵循驼峰命名原则
行为:(方法/功能):见名知意,其他遵循驼峰命名原则
创建类
类:一种数据类型,本身并不占内存空间,
根据所学过的number,string,boolean等类似。
用类创建实例化对象(变量),对象占内存空间
格式:
class 类名(父类列表):
属性
行为
'''
#object:基类,超类,所有类的父类,那么一般没有合适的父类就写object
class Perpose(object):
#定义属性(定义变量)
name = ''
age = 0
height = 0
weught = 0
#定义方法(定义函数)
#注意:方法的参数必须以self当第一个参数
#self代表类的实例(某个对象)
def run(self):
print("run")
def eat(self,food):
print("eat"+food)
二、使用类实例化对象
class Person(object):
name = ''
age = 0
height = 0
weught = 0
def run(self):
print("run")
def eat(self,food):
print("eat"+food)
'''
实例化对象
格式:对象名 = 类名(参数列表)
注意:没有参数,小括号也不能省略
'''
#实例化一个对象
per1 = Person()
print(per1)
print(type(per1))
print(id(per1))
per2 = Person()
print(per2)
print(type(per2))
print(id(per2))
<__main__.Person object at 0x002462D0>
<class '__main__.Person'>
2384592
<__main__.Person object at 0x00246330>
<class '__main__.Person'>
2384688
三、访问对象的属性和方法
class Person(object):
name = ''
age = 0
height = 0
weught = 0
def run(self):
print("run")
def eat(self,food):
print("eat "+food)
def openDoor(self):
print("我已经打开了冰箱门")
def fillEle(self):
print("我已经把大象装进冰箱了")
def colseDoor(self):
print("我已经关上冰箱门了")
per = Person()
'''
访问属性
格式:对象名.属性名
赋值:对象名.属性名 = 新值
'''
per.name = 'tom'
per.age = 18
per.height = 160
per.weight = 80
print(per.name,per.age,per.height,per.weight)
'''
访问方法
格式:对象名.方法名(参数列表)
'''
per.openDoor()
per.fillEle()
per.colseDoor()
per.eat("apple")
tom 18 160 80
我已经打开了冰箱门
我已经把大象装进冰箱了
我已经关上冰箱门了
eat apple
四、对象的初始状态(构造函数)
class Person(object):
#name = ''
#age = 10
#height = 100
#weight = 60
def run(self):
print("run")
def eat(self,food):
print("eat "+food)
def __init__(self,name,age,height,weight):
#print(name,age,height,weight)
#定义属性
self.name = name
self.age = age
self.weight = weight
self.height = height
'''
构造函数:_init_() 在使用类创建对象的时候自动调用
注意:如果不显示的写出构造函数,默认自动添加一个空的构造函数
'''
per = Person("tom",18,170,50)
print(per.name,per.age)
per2 = Person("lilei",19,160,45)
print(per2.name,per2.age)
tom 18
lilei 19