网络编程
位置:首页>> 网络编程>> Python编程>> python的类class定义及其初始化方式

python的类class定义及其初始化方式

作者:嗨皮lemon  发布时间:2023-08-07 11:52:15 

标签:python的类,class定义,初始化

python类class定义及其初始化

定义类,功能,属性

一般类名首字母大写

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

Python定义类时,class,class()和class(object)的区别

  • 1.使用 Python 时, 遇到 class A 和 class A(object) 的写法,在 Py2 中是有概念上和功能上的区别的, 分别称为经典类(旧式类)old-style(classic-style) 与新式类的区别new-style。

  • 2.历史原因:.2.2以前的时候type和object还不统一. 在2.2统一到3之间, 要用class Foo(object)来申明新式类, 因为它的type是 < type &lsquo;type&rsquo; > .不然的话, 生成的类的type就是 < type &lsquo;classobj&rsquo; >

  • 3.为什么要继承object类?主要目的是便于统一操作。在python 3.X中已经默认继承object类

所以,继承object类是为了让自己定义的类拥有更多的属性,以便使用。当然如果用不到,不继承object类也可以。

python2中继承object类是为了和python3保持一致,python3中自动继承了object类。

python2中需要写为如下形式才可以继承object类。

def class(object):

python2中写为如下两种形式都是不能继承object类的,也就是说是等价的。

def class:
def class():

来源:https://blog.csdn.net/weixin_40490880/article/details/81710916

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com