Lecture 5 类和对象
目录
1面向对象程序设计的由来
2类和对象
class Person(object):
def __init__(self): # 类的构造函数,用来初始化对象
self.name = ''
self.age = 0
def display(self): # 类中定义的函数,也称方法
print(self.name,self.age)
if __name__=='__main__':
p=Person() #创建对象
print(p)
print(p.age) #引用对象的属性
print(p.name)
p.age = 25
p.name = 'MaLele'
p.display() #引用对象的方法
<main.Person object at 0x0000000001259A58>
0
MaLele 25
3属性和方法
class Fruit(object):
price = 0 # 类属性
def __init__(self):
self.color = 'red' # 实例属性
zone = 'China' # 局部变量
if __name__=='__main__':
print(Fruit.price) #使用类名调用类变量
apple = Fruit() #实例化apple
print(apple.color)
Fruit.price = Fruit.price+10
print(apple.price)
banana = Fruit()
banana.color = 'yellow'
print(banana.color)
print(banana.price)
0
red
10
yellow
10
2、类的方法
分为公有方法、私有方法
Python使用函数staticmethod()或@staticmethod修饰器将普通的函数转换为静态方法
class Fruit(object):
price = 0 # 定义类变量
def __inin__(self):
self.__color = 'red' # 定义私有变量
def getColor(self):
print(self.__color) # 打印私有变量
@staticmethod # 使用staticmethod修饰器定义静态方法
def getPrice():
print(Fruit.price)
def __getPrice(): # 定义私有函数
Fruit.price = Fruit.price + 10
print(Fruit.price)
count = staticmethod(__getPrice) # 使用staticmethod方法定义静态方法
if __name__=="__main__":
apple = Fruit() # 实例化apple
apple.getPrice() # 使用实例调用静态方法
Fruit.count() # 使用类名调用静态方法
banana = Fruit()
Fruit.getPrice()
Fruit.count()
0
10
10
20
4继承