视代码如诗词,勿要做无所谓的堆砌
class Rectangle():
recs = []#类变量
def __init__(self,w,l):
self.width = w#实例变量
self.length = l
self.recs.append((self.width,
self.length))
def print_size(self):
print("""{} by {}""".
format(self.width,
self.length))
r1 = Rectangle(10,24)
r2 = Rectangle(20,40)
r3 = Rectangle(100,200)
print(Rectangle.recs)
[(10, 24), (20, 40), (100, 200)]
魔法方法
使用魔法方法前
class Lion:
def __init__(self,name):
self.name = name
lion = Lion("Dilbert")
print(lion)
使用魔法方法后
class Lion:
def __init__(self,name):
self.name = name
def __repr__(self):#继承的魔法方法
return self.name
lion = Lion("Dilbert")
print(lion)
class AlwaysPositive:
def __init__(self,number):
self.n = number
def __add__(self,other):#魔法方法
return abs(self.n +
other.n)
x = AlwaysPositive(20)
y = AlwaysPositive(-30)
print(x + y)
is
class Person:
def __init__(self):
self.name = "Bob"
bob = Person()
same_bob = bob
print(bob is same_bob)#指向相同的对象
another_bob = Person()
print(bob is another_bob)#指向不同的对象
x = 10
if x is None:
print("x is None :(")
else:
print("x is not None")
x = None
if x is None:
print("x is None")
if x is not None:
print("x is None:(")
挑战练习
1.向 Square 类中添加一个 square_list 类变量,要求每次新创建一个 Square
对象时,新对象会被自动添加到列表中。
class Square():
resc = []
def __init__(self,att):
self.attend = att
self.resc.append(att)
r1 = Square(10)
r2 = Square(1)
print(Square.resc)
2.修改 Square 类,要求在打印 Square 对象时,打印的信息为图形 4 个边的长
度。例如,假设创建一个 Square(29),则应打印 29 by 29 by 29 by 29。
class Square():
resc = []
def __init__(self,att):
self.attend = att
self.resc.append(att)
print("{} by {} by {} by {}".format(att,att,att,att))
r = Square(29)
3.编写一个函数,接受两个对象作为参数,如果为相同的对象则返回 True,反之
返回 False。
x = input("请输入x:")
y = input("请输入y:")
if x == y:
print(x is y)
else:
print(x is y)