2020-06-20
我不常用 class 還是紀錄一下 :
class Point:
def __init__(self, initX, initY):
self.x = initX
self.y = initY
def getX(self):
return self.x
def getY(self):
return self.y
def distanceFromOrigin(self):
return ((self.x ** 2) + (self.y ** 2)) ** 0.5
def move(self, dx, dy):
self.x = self.x + dx
self.y = self.y + dy
def __str__(self):
return str(self.x)+","+str(self.y)
def reflect_x(self):
return(self.x,-self.y)
print (Point(3, 5))
print (Point(3, 5).reflect_x())
class 繼承
from random import randrange
# Here's the original Pet class
class Pet():
boredom_decrement = 4
hunger_decrement = 6
boredom_threshold = 5
hunger_threshold = 10
sounds = ['Mrrp']
def __init__(self, name = "Kitty"):
self.name = name
self.hunger = randrange(self.hunger_threshold)
self.boredom = randrange(self.boredom_threshold)
self.sounds = self.sounds[:] # copy the class attribute, so that when we make changes to it, we won't affect the other Pets in the class
def clock_tick(self):
self.boredom += 1
self.hunger += 1
def mood(self):
if self.hunger <= self.hunger_threshold and self.boredom <= self.boredom_threshold:
return "happy"
elif self.hunger > self.hunger_threshold:
return "hungry"
else:
return "bored"
def __str__(self):
state = " I'm " + self.name + ". "
state += " I feel " + self.mood() + ". "
# state += "Hunger %d Boredom %d Words %s" % (self.hunger, self.boredom, self.sounds)
return state
def hi(self):
print(self.sounds[randrange(len(self.sounds))])
self.reduce_boredom()
def teach(self, word):
self.sounds.append(word)
self.reduce_boredom()
def feed(self):
self.reduce_hunger()
def reduce_hunger(self):
self.hunger = max(0, self.hunger - self.hunger_decrement)
def reduce_boredom(self):
self.boredom = max(0, self.boredom - self.boredom_decrement)
class Dog(Pet):
sounds = ['Woof', 'Ruff']
def feed(self):
Pet.feed(self)
print("Arf! Thanks!")
d1 = Dog("Astro")
class Bird(Pet):
sounds = ["chirp"]
def __init__(self, name="Kitty", chirp_number=2):
Pet.__init__(self, name) # call the parent class's constructor
# basically, call the SUPER -- the parent version -- of the constructor, with all the parameters that it needs.
self.chirp_number = chirp_number # now, also assign the new instance variable
def hi(self):
for i in range(self.chirp_number):
print(self.sounds[randrange(len(self.sounds))])
self.reduce_boredom()