python基础(二)——类与方法

class human(object):    #定义一个父类
    def __init__(self, name):
        self.__name = name
        self.__walk = True
    def get_name(self):
        return self.__name
    def set_name(self, name):
        self.__name = name
    def walk(self):
        if self.__walk == True:
            print("human walks")
        else:
            print("human not walks")
    def set_walk(self, walk):
        self.__walk = walk
class man(human):   #定义一个子类,继承human类
    def __init__(self, name, has_wife):
        super(man, self).__init__(name)
        self.__has_wife = has_wife
    def marry(self):
        if self.__has_wife == "y":
            print("married")
        else:
            print("not yet")
    def smoke(self):
        print("man smoke")
    def drink(self):
        print("man drink")
class woman(human):     #定义一个子类,继承human类
    def __init__(self, name, has_husband):
        super(woman, self).__init__(name)
        self.__has_husband = has_husband
    def marry(self):
        if self.__has_husband == "y":
            print("married")
        else:
            print("not yet")
    def shopping(self):
        print("woman shopping")
    def make_up(self):
        print("woman make up")
print("begin")
human_a = human("kd")
print(human_a.get_name())
human_a.set_name("dg")
print(human_a.get_name())
human_a.walk()
human_a.set_walk(False)
human_a.walk()
print("\n")
human_b = human("kt")
print(human_b.get_name())
human_b.walk()
print("\n")
human_c = man("kt", "y")
print(human_c.get_name())
human_c.walk()
human_c.marry()
human_c.drink()
human_c.smoke()
print("\n")
human_d = woman("sk", "n")
print(human_d.get_name())
human_d.walk()
human_d.marry()
human_d.shopping()
human_d.make_up()   

输出结果:

begin
kd
dg
human walks
human not walks
kt
human walks
kt
human walks
married
man drink
man smoke
sk
human walks
not yet
woman shopping
woman make up

猜你喜欢

转载自blog.csdn.net/ax478/article/details/79849876