Python类与对象
本文最后更新于 231 天前,其中的信息可能已经有所发展或是发生改变。

类与对象基础操作(类属性,私有,继承,强制访问)

import math
#form ex_point import Point #从ex_point中引用Point类
class Point:
    counter = 0 #类属性(公共的)
    def __init__(self,x=0,y=0,pwd="pass"):#初始化+默认值
        self.x = x
        self.y = y
        self.__pwd = pwd # 私有属性
        Point.counter += 1
    def __prtpass(self):# 私有方法
        print(self.__pwd)

class Circle(Point):#继承
    def __init__(self,x=0,y=0,r=0):
        super().__init__(x,y)
        self.r = r
    def Area(self):#面积
        return math.pi * self.r ** 2
    def Perimeter(self):#周长
        return 2 * math.pi * self.r

class Cylinder(Circle):#继承
    def __init__(self,x=0,y=0,r=0,h=0):
        super().__init__(x,y,r)
        self.h = h
    def Area(self):#表面积(同名方法覆盖)
        return super.Area() * 2 + super.Perimeter() * self.h
    def Volume(self):#体积
        return super.Area() * self.h

aPoint = Point(1,0)
aPoint.x = 100
bPoint = Point()
print(bPoint.x)#输出0

print(Point.counter)#输出2
print(aPoint._Point__pwd)#强制访问私有属性aPoint.__pwd
aPoint._Point__prtpass()#强制访问私有方法aPoint.__prtpass()

aCylinder = Cylinder()

定义矩形和正方形类,添加绘图方法,使用继承

import turtle
class Rectangle:#矩形
    def __init__(self,x=0,y=0,long=0,wide=0):
        self.x = x
        self.y = y
        self.long = long
        self.wide = wide
    def draw(self):
        turtle.setup(400,400,200,200)
        turtle.penup()
        turtle.goto(self.x,self.y)
        turtle.pendown()
        turtle.seth(360)
        turtle.fd(self.long)
        turtle.seth(270)
        turtle.fd(self.wide)
        turtle.seth(180)
        turtle.fd(self.long)
        turtle.seth(90)
        turtle.fd(self.wide)
        turtle.penup()

class Square(Rectangle):
    def __init__(self,x=0,y=0,long=0):
        super().__init__(x,y,long,long)

aRectangle = Rectangle(-60,40,90,30)
aRectangle.draw()
aSquare = Square(0,0,60)
aSquare.draw()
bSquare = Square(-40,-30,30)
bSquare.draw()
turtle.done()#暂停程序,停止画笔绘制,但绘图窗体不关闭
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇