笔者最近在学习Learning python the hard way ,学习了一段时间,感觉类的灵活运用是python学习的难点。编了一段小程序,增加对类使用的理解,也算是完成exercise45的课后作业。
classlist.py
# -*-coding:utf-8 -*-
## Animal is a object
class Animal(object):
pass
## Dog is Animal,调用父类Animal
class Dog(Animal):
def __init__(self, name):
self.satisfy_value = 100
## Dog has name
self.name = name
## Cat is Animal
class Cat(Animal):
def __init__(self, name):
self.satisfy_value = 100
## Cat has name
self.name = name
## Person is a object
class Person(object):
def __init__(self, name, pet_type, pet_name):
## Person has name
self.name = name
## Person has pet
self.pet = None
## Employee is Person
class Employee(Person):
def __init__(self, name, salary, pet_type, pet_name):
## Person has name
super(Employee, self).__init__(name,pet_type,pet_name) ##调用Employee类对Person的属性Name进行赋值
## Employee has salary
self.salary = salary
# -*-coding:utf-8 -*-
from classlist import *
class Game(object):
def __init__(self,person_name, salary, pet_type, pet_name):
self.person_name = person_name
self.salary = salary
self.pet_type = pet_type
self.pet_name = pet_name
self.employee = Employee(self.person_name, self.salary, self.pet_type, self.pet_name) ##将Employee类在Game类中实例化,从而实现类跨模组调用
if self.pet_type == 'cat':
self.cat = Cat(self.pet_name) ##将实例化对象cat作为Game类的__init__()方法中的参数,这种设置需要学习掌握
elif self.pet_type == 'dog':
self.dog = Dog(self.pet_name)
def show_satisfy_value(self):
if self.pet_type == 'cat':
print 'The satisfy value of the cat is %d\n' %self.cat.satisfy_value
elif self.pet_type == 'dog':
print 'The satisfy value of the dog is %d\n' %self.dog.satisfy_value
def feed_pet(self):
if self.pet_type == 'cat':
self.cat.satisfy_value = self.cat.satisfy_value + 4
self.employee.salary = self.employee.salary - 500
print 'Before, the satisfy value is %d' %(self.cat.satisfy_value - 4)
print 'After, the satisfy value is %d\n' %(self.cat.satisfy_value)
elif self.pet_type == 'dog':
self.dog.satisfy_value = self.dog.satisfy_value + 6
self.employee.salary = self.employee.salary - 500
print 'Before, the satisfy value is %d' %(self.dog.satisfy_value - 4)
print 'Now, the satisfy value is %d\n' %(self.dog.satisfy_value)
def remaining(self):
print self.employee.salary
def operation(self):
print 'Please input you operation:\n1.feed_pet\n2.show_satisfy_value\n3.remaining\n4.exit'
action = raw_input(">")
if action == 'show_satisfy_value':
self.show_satisfy_value() ##同一类中的函数调用
elif action == 'feed_pet':
self.feed_pet()
elif action == 'remaining':
self.remaining()
elif action == 'exit':
return exit(0)
else:
print 'The order is wrong, please try agian later.\n'
jack = Game('Jack', 10000, 'cat', 'Tom' )
while True:
jack.operation()
注意事项:
(1)建议所有的类都改为新类,避免对父类赋值时产生错误
新类:class Name(object)
经典类:class Name()
(2)可在Class中定义一个operation()函数,对Class中其他方法进行汇总
Python初学者,如有疑问,欢迎探讨、指正,谢谢~