1 class
Dog:
2
def
setAge(self,age):
3
if age >0
and age <100:
4
self.age = age
5
else:
6
self.age =
0
7
8
def
get_age(self):
9
return self.age
10
11
dog = Dog()
12
13
dog.setAge(-20)
14
print(dog.get_age())
15
16
dog.setAge(10)
17
print(dog.get_age())
1 class
Dog:
2
3
# 私有方法 加 __
4
def
__test(self):
5
print('十八年后再来')
6
7
def
test(self,age):
8
if age <18:
9
self.__test()
10
else:
11
print('已成年')
12
13
dog = Dog()
14
dog.test(10)
15
print('='*40)
16
dog.test(20)
1 class
Dog:
2
# 被杀死前调用,就是引用计数为0时
3
def
__del__(self):
4
print('over')
5
6
7
dog1 = Dog()
8
dog2 = dog1
9
10
print('-'*10)
11 del dog1
12
print('-'*10)
13 del dog2
14
print('-'*10)
私有的并不会被继承
1 class
Animal:
2
def
eat(self):
3
print('吃')
4
5
def
drink(self):
6
print('喝')
7
8
def
sleep(self):
9
print('睡')
10
11
#在类名后加上(父类)
12
#父类的方法,子类可以用
13
#同一父类下的子类,方法不可以相互调用
14 class
Dog(Animal):
15
def
bark(self):
16
print('汪汪')
17
18 class
Cat(Animal):
19
def
catch(self):
20
print('抓老鼠')
21
22
wangcai = Dog()
23
wangcai.eat()
24
25
tom = Cat()
26
tom.eat()
27
28 class
XiaoTian(Dog):
29
def
fly(self):
30
print('飞')
31
#重写,即重写父类的方法,调用时,会调用自己的方法文不会调用父类的
32
def
eat(self):
33
print('吞')
34
#调用被重写的父类的方法
35
Animal.eat(self)
36
37
# 子类可以调用爷爷的方法,子子孙孙都可以用长辈的方法
38
xiaoTianQuan = XiaoTian()
39
xiaoTianQuan.fly()
40
xiaoTianQuan.bark()
41
xiaoTianQuan.eat()
1 class
Base(object):
2
def
test(self):
3
print('--Base')
4
5 class
A(Base):
6
def
test1(self):
7
print('--test1')
8
9
def
test(self):
10
print('A')
11 class
B(Base):
12
def
test2(self):
13
print('--test2')
14
15
def
test(self):
16
print('B')
17 class
C(A,B):
18
def
test(self):
19
print('--test3')
20
21
22
c =C()
23
c.test1()
24
c.test2()
25
# 优先会在C中去找,之后A之后B之后Base,当找到后就会停止查找
26
c.test()
多态:定义时的类型和运行时的类型不一样,此时就成为多态
1 class
Dog(object):
2
def
print_self(self):
3
print('大家好,我是***')
4
5 class
xiaoTian(Dog):
6
def
print_self(self):
7
print('hello
everybody,我是神兽')
8
9 def
introduce(temp):
10
#此方法并不确定调用调用谁的方法,这就是多态
11
temp.print_self()
12
13
dog1 =Dog()
14
dog2 =xiaoTian()
15
16
introduce(dog1)
17
introduce(dog2)
1 class
Tool(object):
2
#属性
3
num =
0
#类属性
4
#方法
5
def
__init__(self,new_name):
7
Tool.num +=1
8
9
tool1 = Tool('锤子')
10
tool2 = Tool('电锯')
11
tool3 = Tool('铁锹')
12
print(Tool.num)
1 class
Game(object):
2
#类属性
3
num =
0
4
5
#实例方法
6
def
__init__(self):
7
#实例属性
9
10
#类方法
11
@classmethod
12
def
addNum(cls):
#cls 是class 的缩写
13
cls.num =
10
14
15
#静态方法
16
@staticmethod
17
def
printMenu():
18
print('-'*40)
19
20
game = Game()
21
Game.addNum()#用类名来调用类方法
22
print(Game.num)
23
game.addNum()#用对象来调用类方法
24
print(Game.num)
25
26
Game.printMenu()#用类名调用静态方法
27
game.printMenu()#用对象调用静态方法