python的类class定义及其初始化

  • Post author:
  • Post category:python

定义类,功能,属性
一般类名首字母大写


class Calculator:
#名字和价格是属性
    name="jisuanqi" 
    price=28
    #定义的四个函数是功能
    def add(self,x,y):
        print(self.name)#这里指的是函数的属性-名字
        result=x+y
        print(result)
    def subtract(self,x,y):
        print(x-y)
    def multiply(self,x,y):
        print(x*y)
    def divide(self,x,y):
        print(x/y)

calc=Calculator()
print(calc.name)#jisuanqi
print(calc.price)#28
print(calc.add(1,2))#3
print(calc.subtract(10,2))#8

输出:
jisuanqi
28
jisuanqi
3
None
8
None

类的初始_init_


class Calculator:
    name="jisuanqi" #这是固有属性
    price=28
    #初始化,里面的参数可以自己定义
    def __init__(self,name,price,hight,width,weight):
        self.name=name
        self.price=price
        self.h=hight
        self.w=width
        self.weight=weight

    def add(self,x,y):
        print(self.name)
        result=x+y
        print(result)
    def subtract(self,x,y):
        print(x-y)
    def multiply(self,x,y):
        print(x*y)
    def divide(self,x,y):
        print(x/y)
#这里必须传入参数才可以
calc=Calculator('good calc',280,30,30,100)
print(calc.name)#jisuanqi
print(calc.weight)#100
print(calc.price)#280

输出结果:
good calc
100
280


版权声明:本文为weixin_40490880原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。