-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path01_class.py
More file actions
56 lines (42 loc) · 1.39 KB
/
01_class.py
File metadata and controls
56 lines (42 loc) · 1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# python 使用特殊方式调用类中的私有方法
class Fruit(object):
price = 0
name = ''
def __init__(self, oName='Fruit'):
self.__color = 'red'
self.ciity = 'Kunming'
Fruit.name = oName
def __outputColor(self): # 定义私有方法
print(self.__color)
def output(self): # 调用私有方法
self.__outputColor()
#类方法,用classmethod来进行修饰,方法可以判断出自己是通过基类被调用,还是通过某个子类被调用
@ classmethod
def getName(cls):
return cls.name
@ staticmethod
def getPrice():
return Fruit.price
@ staticmethod
def setPrice(p):
Fruit.price = p
class Orange(Fruit): # 继承Fruit,测试classmethod
"""docstring for orange"""
def __init__(self, oName='orange'):
super(Orange, self).__init__(oName)
# 主程序
apple = Fruit('apple')
apple.output()
print(Fruit.getPrice())
Fruit.setPrice(10)
print(Fruit.getPrice())
print(apple._Fruit__color) # 使用特殊方式调用类的私有成员
print(apple._Fruit__outputColor) # 使用特殊方式调用类的私有方法
print(apple.getName()) # 测试classmethod step 01
orange = Orange()
print(orange.getName()) # 测试classmethod step 02
# 多态
print('apple is fruit',isinstance(apple, Fruit))
print('apple is orange',isinstance(apple, Orange))
print('orange is fruit',isinstance(orange, Fruit))
print('orange is orange',isinstance(orange, Orange))