Python创建对象

来源:互联网 发布:java set集合获取元素 编辑:程序博客网 时间:2024/06/10 13:29

面向对象的编程

将一类事物去点细枝末节的东西分为属性(property)和方法(method())

属性(property)是静态的,比如姓名,性别,身高,体重等等

方法(method())是动态的,比如吃饭,喝水,跳舞,运动等等

#类的构造方法

#类(class)的创建以关键字class开头,类名首字母大写

class Student:

# def __init__(self,参数1,参数2...)    只能修改参数1,参数2..

def __init__(self,name,gender,age,score):


        self.name=name#前面有一个tab键的间隔


        self.gender=gender#类的构造方法


  def interduce(self):
        print("My name is {0}, I am {1}, I am {2} years old, My score is {3}".format(self.name,self.gender,str(self.age),str(self.score)))
        print("nice to meet you")
def impove(self,count):#count为数值型,可以是正数,可以是负数
        self.score=self.score+count#修改score的值

#上面是类的构造



tom=Student("tom","boy",24,90) #初始化类
tom.interduce() #类的方法调用
 
tom.impove(-19) #类的方法调用


tom.interduce() #类的方法的调用



#装饰器   方法一
#定义一个函数,带参数
def add(function):
    def aa():#在函数内部定义一个方法
        #返回另一个方法+需要添加的内容
        return function()+"  hehe"
    return aa()#这是a函数的返回值
def b():#需要调用的方法
    return "nihao"
s=add(b)#方法调用
print(s)

#方法二

#定义一个函数,带参数
def add(function):
    def aa(): #在函数内部定义一个方法


        #返回另一个方法+需要添加的内容


        return function()+"  python"


    return aa()#这是a函数的返回值


def b():#需要调用的方法


    return "hello"


s=add(b)#方法调用


print(s)

结果:hello python


@add    #将这个函数加到add()方法里作为参数

def c():    #定义从c()


    return "你好"   


print(c)    #调用从c()

结果:你好 python

0 0