我想在同一对象上使用抽象(来自父类)和接口,而不必进行强制转换。
我已经搜索过它,看来铸造是用于这种目的的常用方法。
我有一个程序,其中Dog
扩展了Animal
实现Friendly
动物让狗yell()
和友好的(接口)让狗hug()
在使用Friendly(Interface)之前,我曾经这样做过:
Animal dog = new Dog();
dog.yell();
但是现在,要添加接口,我必须将狗强制转换为友好类型,以便他可以拥抱():
Animal dog = new Dog();
dog.yell();
((Friendly) dog).hug();
有什么更好的方法可以做到这一点,因为我的老师告诉我,铸造通常是个坏主意。
答案 0 :(得分:1)
如果需要避免强制转换,则必须使用from PIL import ImageGrab
import tkinter as tk
import tkinter.messagebox as tkMessageBox
import turtle
WIDTH, HEIGHT = 500, 400
IMG_FILENAME = 'turtlescreen.png' # Extension determines file format.
def draw_stuff(canvas):
screen = turtle.TurtleScreen(canvas)
t = turtle.RawTurtle(screen.getcanvas())
t.speed(0) # Fastest.
t.pencolor('black')
t.hideturtle()
# Draw a snowflake.
size = 10
def branch(size):
for i in range(3):
for i in range(3):
t.forward(10.0*size/3)
t.backward(10.0*size/3)
t.right(45)
t.left(90)
t.backward(10.0*size/3)
t.left(45)
t.right(90)
t.forward(10.0*size)
# move the pen into starting position
t.penup()
t.forward(10*size)
t.left(45)
t.pendown()
# Draw 8 branches.
for i in range(8):
branch(size)
t.left(45)
print('done')
def getter(root, widget):
x = root.winfo_rootx() + widget.winfo_x()
y = root.winfo_rooty() + widget.winfo_y()
x1 = x + widget.winfo_width()
y1 = y + widget.winfo_height()
return ImageGrab.grab().crop((x, y, x1, y1))
def save_file(root, canvas, filename):
""" Convert the Canvas widget into a bitmapped image. """
# Get image of Canvas and convert it to bitmapped image.
img = getter(root, canvas).convert('L').convert('1')
img.save(IMG_FILENAME) # Save image file.
tkMessageBox.showinfo("Info", "Image saved as %r" % filename, parent=root)
# main
root = tk.Tk()
canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT,
borderwidth=0, highlightthickness=0)
canvas.pack()
btn_frame = tk.Frame(root)
btn_frame.pack()
btn1 = tk.Button(btn_frame, text='Draw', command=lambda: draw_stuff(canvas))
btn1.pack(side=tk.LEFT)
btn2 = tk.Button(btn_frame, text='Save',
command=lambda: save_file(root, canvas, IMG_FILENAME))
btn2.pack(side=tk.LEFT)
btn3 = tk.Button(btn_frame, text='Quit', command=root.quit)
btn3.pack(side=tk.LEFT)
root.mainloop()
作为Dog
变量的类型:
dog
尽管如此,您并没有编程到Dog dog = new Dog();
dog.yell();
dog.hug();
和Friendly
接口,而在正确使用抽象的情况下,您最好这样做。
如果必须像这样在代码中将Animal
声明为dog
或Animal
,那么您出于错误的原因使用了抽象。
...我的老师告诉我,铸造通常是个坏主意。
铸造是没人喜欢的事情,但是每个人都必须在必要时这样做。