This website requires JavaScript.

Python Class 类 示例

#!/usr/bin/python3

class AnimalActions:
    def quack(self): return self.strings['quack']
    def feathers(self): return self.strings['feathers']
    def bark(self): return self.strings['bark']
    def fur(self): return self.strings['fur']

class Duck(AnimalActions):
    strings = dict(
        quack = "Quaaaaak!",
        feathers = "The duck has gray and white feathers.",
        bark = "The duck cannot bark.",
        fur = "The duck has no fur."
    )

class Person(AnimalActions):
    strings = dict(
        quack = "The person imitates a duck.",
        feathers = "The person takes a feather from the ground and shows it.",
        bark = "The person says woof!",
        fur = "The person puts on a fur coat."
    )

class Dog(AnimalActions):
    strings = dict(
        quack = "The dog cannot quack.",
        feathers = "The dog has no feathers.",
        bark = "Arf!",
        fur = "The dog has white fur with black spots."
    )

def in_the_doghouse(dog):
    print(dog.bark())
    print(dog.fur())

def in_the_forest(duck):
    print(duck.quack())
    print(duck.feathers())

def main():
    donald = Duck()
    john = Person()
    fido = Dog()

    print("- In the forest:")
    for o in ( donald, john, fido ):
        in_the_forest(o)

    print("- In the doghouse:")
    for o in ( donald, john, fido ):
        in_the_doghouse(o)

if __name__ == "__main__": main()
__author__ = 'Master'

class Duck:
    def __init__(self, **kwargs):
        self._color = kwargs.get('color', 'while') # 如果没参数传进来就用括号中的值代替

    def quack(self):
        print('Quaaack!')

    def walk(self):
        print("Walks like a duck.")

    def set_color(self, color):
        self._color = color

    def get_color(self):
        return self._color

def main():
    donald = Duck(color='blue', aa='sadfdf')
    print(donald.get_color())

if __name__ == '__main__':
    main()
#------------------------------------------
#上面的的类多带几个参数处理起来就麻烦了,可以改成以下形式
#------------------------------------------
class Duck:
    def __init__(self, **kwargs):
        self.variables = kwargs

    def quack(self):
        print('Quaaack!')

    def walk(self):
        print("Walks like a duck.")

    # def set_color(self, color):
    #     self.variables['color'] = color
    #
    # def get_color(self):
    #     return self.variables.get('color', None)

    def set_variable(self, k, v):
        self.variables[k] = v

    def get_variable(self, k):
        return self.variables.get(k, None)

def main():
    donald = Duck(feet=2)
    print(donald.get_variable('feet'))

if __name__ == '__main__':
    main()
 
# -*- coding:UTF-8 -*-
# !/usr/bin/python3

# simple fibonacci series
# the sum of two elements defines the next set

class Fibonacci:
    def __init__(self, a, b):  # 构造函数..初始化变量
        self.a = a
        self.b = b

    def series(self):
        while True:
            yield(self.b)
            self.a, self.b = self.b, self.a + self.b

f = Fibonacci(0, 1)
for r in f.series():
    if r > 100:
        break
    print(r, end=' ')
实现一个range
class inclusive_range:
    def __init__(self, *args):
        numargs = len(args)
        if numargs < 1:
            raise TypeError('requires at least one argument')
        elif numargs == 1:
            self.stop = args[0]
            self.start = 0
            self.step = 1
        elif numargs == 2:
            (self.start, self.stop) = args
            self.step = 1
        elif numargs == 3:
            (self.start, self.stop, self.step) = args
        else:
            raise TypeError('expected at most 3 arguments, got{}'.format(numargs))

    def __iter__(self):  # __iter__ 表示对象是一个迭代(iterable)对象
        i = self.start
        while i <= self.stop:
            yield i
            i += self.step

def main():
    # o = range(25)
    o = inclusive_range(5, 25)
    for i in o:
        print(i, end=' ')

if __name__ == "__main__":
    main()
decorators
class Duck:
    def __init__(self, **kwargs):
        self.properties = kwargs

    def quack(self):
        print('Quaaack!')

    def walk(self):
        print('Walks like a duck.')

    def get_properties(self):
        return self.properties

    def get_property(self, key):
        return self.properties.get(key, None)

    @property
    def color(self):
        return self.properties.get('color', None)

    @color.setter
    def color(self, c):
        self.properties['color'] = c

    @color.deleter
    def color(self):
        del self.properties['color']

def main():
    donald = Duck()
    donald.color = 'blue'
    print(donald.color)

if __name__ == "__main__":
    main()
 
0条评论
avatar