首页 技术 正文
技术 2022年11月14日
0 收藏 604 点赞 3,454 浏览 1895 个字

类的定义

基本形式:
class ClassName(object):
Statement

1.class定义类的关键字

2.ClassName类名,类名的每个单词的首字母大写。

3.object是父类名,object是一切类的基类。在python3中如果继承类是基类可以省略不写。

类的实例

class Fruits:
fruits = 'xxxxxx' # 类属性
def __init__(self,name,color,weight=90):
self.name = name
self.color = color
self.weight = weight
self.fruits = 'yyyyy' # 实例属性
def show(self):
print('我的重量是%s'% self.color)class Apple(Fruits):
def __init__(self,color,weight,shape):
Fruits.__init__(self,'apple',color,weight) # 调用父类的初始化函数
self.shape = shape
def eat(self):
print('被吃掉了。。。。')ap1 = Apple('red',100,'圆的')
# 类的实例化
fr1 = Fruits('apple','red')
fr2 = Fruits('banana','yellow')
fr3 = Fruits('apple','green',100)

多继承

class A:
def show(self):
print('AAAAA')class B:
def fun(self):
print('BBBBB')class C(A,B):
passx = C()

实例调用:

__init__    初始化
__repr__ c1
__str__ print (c1 )(如果类里面先定义了__repr__的话print x时也会返回对应的
__call__ c1() 使实例可被调用
ss = 'a\nb'
class Rectangle:
def __init__(self,width,height):
self.width = width
self.height = height
def __str__(self):
return '宽为%s,高为%s' % (self.width,self.height)
def __repr__(self):
return '面积为%s' % self.area()
def __call__(self):
return 'hahahha'
def area(self):
return self.width*self.height
def __add__(self,other):
if isinstance(other,Rectangle):
return self.area()+other.area()

运算符魔法方法:

__add__(self,other)     x+y
__sub__(self,other) x-y
__mul__(self,other) x*y
__mod__(self,other) x%y
__iadd__(self,other) x+=y
__isub__(self,other) x-=y
__radd__(self,other) y+x
__rsub__(self,other) y-x
__imul__(self,other) x*=y
__imod__(self,other) x%=y

装饰器

@property 装饰过的函数返回的不再是一个函数,而是一个property对象
装饰过后的方法不再是可调用的对象,可以看做数据属性直接访问。
@staticmethod 把没有参数的函数装饰过后变成可被实例调用的函数,
函数定义时是没有参数的。
@classmethod 把装饰过的方法变成一个classmethod类对象,既能能被类调用又能被实例调用。
注意参数是cls代表这个类本身。而是用实例的方法只能被实例调用。
class Rectangle:
def __init__(self,width,height):
self.width = width
self.height = height
@property
def area(self):
return self.width*self.height
@staticmethod
def fun():
return 'xxxxxx'
@classmethod
def show(cls):
return 'yyyyyy'c1 = Rectangle(3,4)
c2 = Rectangle(4,5)def fun1(x):
def fun2(y):
return x(y) + 100
return fun2@fun1 # ff = fun1(ff)
def ff(y):
return y*y
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,997
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,511
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,356
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,139
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,770
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,848