失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > python类定义的讲解_python面向对象 自定义类等使用实例讲解

python类定义的讲解_python面向对象 自定义类等使用实例讲解

时间:2020-02-22 13:33:55

相关推荐

python类定义的讲解_python面向对象 自定义类等使用实例讲解

python 面向对象相对别的语言来说缺少两个功能:

1、python不具备重载,重载是指在同一个类中,使得方法有相同的名称,但是有不同的参数列表,但由于python函数具有强大的参数处理功能,因此这不是一个问题。

2、python不存在强制数据隐私的机制,不过若想创建属性(实例变量或方法)时在属性名前以两个下划线引导,python就会阻止无心的访问,因此可以认为是私有的。

如果一个方法是预定义的特殊方法,则应该在方法名前后加上双下划线,例如__sub__()和__add__()。

一、自定义类

1、方法一

class className:

suite

2、方法二

class className(base_class):

suite

二、属性与方法

import math

class Point(object):

def __init__(self,x,y):

self.x = x

self.y = y

def __eq__(self,other):

return self.x == other.x and self.x == other.y

def distance_from_origin(self):

return math.hypot(self.x,self.y)

def __str__(self):

return '({0.x},{0.y})'.format(self)

a = Point(1,2)

b = Point(2,2)

b.distance_from_origin()

Point.distance_from_origin(b)

a == b

str(a)

可预定义的比较方法如下:

默认情况下,自定义类的所有实例都是可哈希运算的,因此,可对其调用hash(),也可以将其作为字典的键,或存储在集合中。但是如果重新实现了__eq__(),实例就不再是可哈希运算的了。

为了避免不适当的比较,可以使用如下三种方法:

使用断言

assert isintance(object,Class),'object is not in the Class'

产生TypeError异常

if not isinstance(object,Class):

raise TypeError('object is not in the Class')

返回NotImplemented

if not isinstance(object,Class):

return NotImplement-ented

如果返回了NotImplemented,Python就会尝试调用other.__eq__(self)来查看object是否支持与Class类的比较,如果也没有类似的方法,Python将放弃搜索,并产生TypeError异常。

内置的isinstance()函数以一个对象与一个类为参数,如果该对象属于该类(或类元组中的某个类),或属于给定类的基类,就返回True

使用super()

使用super()函数可以使用基类的方法

def __init__(self,x,y,radius):

super().__init__(x,y)

self.radius = radius

在使用super()时,可以不用写self参数。

使用特性进行属性存取控制

一些方法返回一个单独的值,从用户的角度讲,可以将方法可以当做数据属性使用。以下是一个实例

class Circle(object):

def __init__(self,radius):

self.radius = radius

def area(self):

return self.radius * 2

area = property(area)

c = Circle(4)

c.area

或可写为

class Circle(object):

def __init__(self,radius):

self.radius = radius

@property

def area(self):

return self.radius * 2

c = Circle(4)

c.area

提供了一种验证数据有效性的方法

class Circle(object):

def __init__(self,x,y,radius):

self.radius = radius

self.x = x

self.y = y

def area(self):

return self.radius * 2

area = property(area)

@property

def radius(self):

return self.__radius

@radius.setter

def radius(self,radius):

assert radius > 0,"radius must be nonzero and non-negative"

self.__radius = radius

c = Circle(1,-2,4)

c.area

希望与广大网友互动??

点此进行留言吧!

如果觉得《python类定义的讲解_python面向对象 自定义类等使用实例讲解》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。