python 问题 关于类的

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 问题 关于类的相关的知识,希望对你有一定的参考价值。

class Point:
"""A class to represent a two-dimensional point"""
def __init__(self):
self.x = 0
self.y = 0

class Rectangle:
def __init__(self):
self.corner = Point()
self.width = 100
self.height = 100

def equals(self, otherRect):
"""
Test if this rectangle is equal to otherRect. Deep equality should be tested.
>>> r1 = Rectangle()
>>> r1.corner.x = 50
>>> r1.corner.y = 40
>>> r1.width = 200
>>> r2 = Rectangle()
>>> r2.corner.x = 50
>>> r2.corner.y = 40
>>> r2.width = 200
>>> r1.equals(r2)
True
>>> r2.height = 200
>>> r1.equals(r2)
False
"""
#add an equals(self, otherRect) method to the Rectangle class. the method should do a deep quality check. Recall that deep equality means that equals should return True if the contents of the structure are equal and False otherwise. here above is the skeleton and two doctests for the method.
#就是说在上面的equals 里添加语句 让上面的测试通过。 我实在不会做 希望大家能帮我这个忙,谢谢了!

class Point:
"""A class to represent a two-dimensional point"""
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __eq__(self,other):
return self.x == other.x and self.y == other.y

class Rectangle:
def __init__(self, corner=Point(), width=100, height=100):
self.corner = corner
self.width = width
self.height = height

def equals(self, otherRect):
return self.corner == otherRect.corner \
and self.width == otherRect.width \
and self.height == otherRect.height

def __eq__(self, otherRect):
return self.equals(otherRect)
"""
Test if this rectangle is equal to otherRect. Deep equality should be tested.
>>> r1 = Rectangle()
>>> r1.corner.x = 50
>>> r1.corner.y = 40
>>> r1.width = 200
>>> r2 = Rectangle()
>>> r2.corner.x = 50
>>> r2.corner.y = 40
>>> r2.width = 200
>>> r1.equals(r2)
True
>>> r2.height = 200
>>> r1.equals(r2)
False
"""追问

为什么不能写成
if self.corner == otherRect.corner and self.width == otherRect.width:
return True
else:
return self.height == otherRect.height???

追答

相等的逻辑应该是几个数据属性完全一样: corner一样, width一样, 且 height也一样;
任意一个属性有差异就是不同

参考技术A return self.width == otherRect.width and self.height == otherRect.height and self.corner.x == otherRect.corner.x and self.corner.y == otherRect.corner.y

以上是关于python 问题 关于类的的主要内容,如果未能解决你的问题,请参考以下文章

Watir 问题关于存在于类中以用于测试目的

C++中关于类对象的初始化问题

Python functools.wraps 等价于类

Python 错误:此方法仅适用于类,不适用于实例

Python安全 | Flask-jinja2 SSTI 利用手册

类与类的关系(横向关系)