Δημοσιεύτηκε: 10 Αύγ 2009, 16:11
από Luke
Μία προτεινόμενη "λύση" από εμένα:
Spoiler: show
Κώδικας: Επιλογή όλων

#! C:\Python30\python.exe
# Filename: Ex_5th_lesson.py

class Animal:
population = 0

def __init__(self, type, length, height, weight):
self.type = type
self.length = length
self.height = height
self.weight = weight
Animal.population += 1

def __del__(self):
Animal.population -= 1

def printInfo(self):
print('Type: "{0}" Length: "{1:g}" Height: "{2:g}" Weight: "{3:g}"'.format(self.type,
self.length, self.height, self.weight), end=" ")

@staticmethod
def howMany():
print('Totally {0} animals in the zoo'.format(Animal.population))
#howMany = staticmethod(howMany)


class Mammal(Animal):
def __init__(self, type, length, height, weight, feather):
Animal.__init__(self, type, length, height, weight)
self.feather = feather

def __del__(self):
Animal.__del__(self)

def printInfo(self):
Animal.printInfo(self)
print('Feather: "{0}"'.format(self.feather))


class NonMammal(Animal):
def __init__(self, type, length, height, weight, feeding):
Animal.__init__(self, type, length, height, weight)
self.feeding = feeding

def __del__(self):
Animal.__del__(self)

def printInfo(self):
Animal.printInfo(self)
print('Feeding: "{0}"'.format(self.feeding))


elephant = Mammal('elephant', 5.0, 4.0, 1000.0, False)
dolphin = Mammal('dolphin', 4.0, 0.8, 70.0, False)
snake = NonMammal('snake', 3.0, 0.07, 2.0, 'other animals')
hawk = NonMammal('hawk', 70.0, 30.0, 15.8, 'predator')

Animal.howMany()

elephant.printInfo()
dolphin.printInfo()
snake.printInfo()
hawk.printInfo()

elephant.height = 6.0
elephant.printInfo()

del elephant
del dolphin
del snake
del hawk

Animal.howMany()


sokoban4ever έγραψε:
Δώστε ένα χαρακτηριστικό σε ένα ήδη δημιουργημένο αντικείμενο ζώο
παρόλο που δεν υπάρχει μέθοδος
Π.χ
Κώδικας: Επιλογή όλων
elefantas.mitι = 'proboskida'

τι παρατηρείτε ;

Spoiler: show
Αλλάζει η τιμή της μεταβλητής. :)
Υποθέτω ότι αυτό συμβαίνει επειδή όλες οι μεταβλητές είναι public. Δοκίμασα και με μία private μεταβλητή (με διπλή κάτω παύλα) και δεν έγινε κάποια αλλαγή.
Το κακό που βρήκα είναι ότι όταν πας να κάνεις εκχώρηση με τον παραπάνω τρόπο είτε σε private είτε σε μεταβλητή που δεν υπάρχει ο interpreter της python δε βγάζει σφάλμα. :(