百行代码入门Python - Chapter 4

以下代码均采用Python 3.5.2编写。新建一个名为HelloWorld.py的文件,当然名字无所谓,输入以下代码:

#Class
class Bird(object):
    feather= True
    reproduction="egg"
    def chirp(self, sound="some sound"):
        print(sound)
    def set_color(self,color):
        self.color=color
        return color

#property
class Chicken(Bird):
    fly=False
    def __init__(self, age):
        self.age=age
    def get_adult(self):
        if self.age>1.0:
            return True
        else:
            return False
    adult=property(get_adult)

summer=Chicken(2)
print(summer.adult)

class num(object):
    def __init__(self, value):
        self.value=value
    def get_neg(self):
        return -self.value
    def set_neg(self, value):
        self.value=-value
    def del_neg(self):
        print("value is also deleted")
        del self.value
    neg=property(get_neg,set_neg,del_neg,"I'm negative")

x=num(1.1)
print(x.neg)
x.neg=-22
print(x.value)
print(num.neg.__doc__)
del x.neg

#__getattr__
class Goose(Bird):
    fly=True
    def __init__(self, age):
        self.age=age
    def __getattr__(self,name):
        if name=="adult":
            if self.age>1.0:
                return True
            else:
                return False
        else:
            raise AttributeError(name)

summer = Goose(2)
print(summer.adult)
summer.age=0.5
print(summer.adult)
#__getattr__ can only check the attributes not in __dict__, __getattribute__ can check all of the attributes

#parameter trans
def example_f(x):
    print(id(x))
    x=100
    print(id(x))

a=1
print(id(a))
example_f(a)
print(a)

def example_f2(x):
    x[0]=100
    print(x)

a=[1,2,3]
example_f2(a)
print(a)

#func parameter
def square_sum(a,b):
    return a**2+b**2
def cubic_sum(a,b):
    return a**3+b**3
def argument_demo(f,a,b):
    return f(a,b)

print(argument_demo(square_sum,3,5))
print(argument_demo(cubic_sum,3,5))

#func return
def line_conf():
    def line(x):
        return 2*x+1
    return line

my_line=line_conf()
print(my_line(5))

将后面尚未读到的代码注释掉,一段一段查看执行效果,即可轻松入门Python。

上一篇:meta 之 viewport


下一篇:集成剪枝分类算法的Bagging集成学习算法示例