⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 shapefactory1.py

📁 this is the most basic to learn python
💻 PY
字号:
#: c05:shapefact1:ShapeFactory1.py
# A simple static factory method.
from __future__ import generators
import random

class Shape(object):
  # Create based on class name:
  def factory(type):
    #return eval(type + "()")
    if type == "Circle": return Circle()
    if type == "Square": return Square()
    assert 1, "Bad shape creation: " + type
  factory = staticmethod(factory)

class Circle(Shape):
  def draw(self): print "Circle.draw" 
  def erase(self): print "Circle.erase" 

class Square(Shape):
  def draw(self): print "Square.draw" 
  def erase(self): print "Square.erase" 

# Generate shape name strings:
def shapeNameGen(n):
  types = Shape.__subclasses__()
  for i in range(n):
    yield random.choice(types).__name__

shapes = \
  [ Shape.factory(i) for i in shapeNameGen(7)]

for shape in shapes:
  shape.draw()
  shape.erase()
#<hr>
output = '''
Square.draw
Square.erase
Circle.draw
Circle.erase
Square.draw
Square.erase
Circle.draw
Circle.erase
Circle.draw
Circle.erase
Circle.draw
Circle.erase
Square.draw
Square.erase
'''

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -