1. 基本概念
2. 类和对象
例如:
3. 面向对象基础语法
class Cat:
def eat(self):
print('小猫爱吃鱼')
def drink(self):
print ('小猫爱喝水')
tom = Cat()
tom.drink()
tom.eat()
接上面的程序
print(tom)
address = id(tom)
print('%d' % address)
print('%x' % address)
很明显不是。
class Cat:
def eat(self):
print('%s 爱吃鱼' % self.)
def drink(self):
print ('%s 爱喝水' % self.)
tom = Cat()
tom.drink()
tom.eat()
print(tom)
kacy = Cat()
kacy.eat()
kacy.drink()
print(kacy)
self 是地址。很明显不是我们想要的结果。
class Cat:
def eat(self):
print('%s 爱吃鱼' % self.name)
def drink(self):
print ('%s 爱喝水' % self.name)
tom = Cat()
tom.name = 'tom'
tom.drink()
tom.eat()
print(tom)
kacy = Cat()
kacy.name = 'kacy'
kacy.eat()
kacy.drink()
print(kacy)
4. 初始化
class Cat:
def __init__(self,new_name):
self.name = new_name
def eat(self):
print('%s 爱吃鱼' % self.name)
def drink(self):
print ('%s 爱喝水' % self.name)
tom = Cat('tom')
tom.drink()
tom.eat()
print(tom)
kacy = Cat('kacy')
kacy.eat()
kacy.drink()
print(kacy)
5. 内置方法和属性
class Cat:
def __init__(self,new_name):
self.name = new_name
print('%s 我来了' % self.name)
def __del__(self):
print('%s 我去了' % self.name)
tom = Cat('tom')
print('=' * 10)
class Cat:
def __init__(self,new_name):
self.name = new_name
print('%s 我来了' % self.name)
def __del__(self):
print('%s 我去了' % self.name)
tom = Cat('tom')
del tom
print('=' * 10)
def __del__(self):
这个函数的意义就是在销毁之前再做点什么。
class Cat:
def __init__(self,new_name):
self.name = new_name
print('%s 我来了' % self.name)
def __del__(self):
print('%s 我去了' % self.name)
tom = Cat('tom')
print(tom)
之前我们也讲过,定义一个对象,打印这个对象,打印的是他的类以及十六进制的地址。但是我们并不想这样。
class Cat:
def __init__(self,new_name):
self.name = new_name
print('%s 来了' % self.name)
def __del__(self):
print('%s 去了' % self.name)
# 必须返回一个字符串
def __str__(self):
return('我是小猫 %s' % self.name)
tom = Cat('tom')
print(tom)
1