首页 > 编程语言 > 详细

读书笔记之python深入面向对象编程

时间:2020-05-23 23:50:23      阅读:73      评论:0      收藏:0      [点我收藏+]

# L14 深入面向对象编程
#14.1类有2种类型的变量:类变量与实例变量
class Rectangle():
    def __init__(self,w,l):
        self.width=w
        self.len=l
    def print_size(self):
        print("""{}by""".format(self.width,self,len))
my_rectangle = Rectangle(10,24)
my_rectangle.print_size()
#类变量可以在不使用全局变量的情况下,在类的所有实例之间共享数据
class Rectangle():
#在类中添加了recs的类变量,在__init__方外定义的
    recs=[]
    def __init__(self,w,l):
        self.width=w
        self.len=l
        self.recs.append(self.width,self,len)
    def print_size(self):
        print("""{}by{}""".format(self.width,self.len))
r1=Rectangle(10,24)
r2=Rectangle(20,40)
r3=Rectangle(100,200)
print(Rectangle(100,200))
#魔法方法
class Lion:
    def __init__(self,name):
        self.name=name
    def __repr__(self):
        return self.name
lion = Lion("Dilbert")
print(lion)
#表达式中的操作数必须有一个运算符是用来对表达式求值的魔法方法。
# 例如:在表达式2+2中,每个整型数对象都有一个叫 _ _add_ _的方法。
#Python在对表达式求值时就会调用该方法
class AlwaysPositive:
    def __init__(self,number):
        self.n=number
    def __add__(self, other):
        return abs(self.n+other.n)
x=AlwaysPositive(-20)
y=AlwaysPositive(10)
print(x+y)
# 关键字is返回True /False,
class Person:
    def __int__(self):
        self.name=‘Bob‘
bob=Person()
same_bob=bob
print(bob is same_bob)
another_bob=Person()
print(bob is another_bob)

#关键字is还可以检查变量是否为None
x=10
if x is None:
    print("x is Noe :( ")
else:
    print("x is not None")
x=None
if x is None:
    print("x is None")
else:
    print("x is None:(")
 
练习题
技术分享图片
技术分享图片

 

 


答案
1.
class Shape():
    def what_am_i(self):
        print("I am a shape.")

class Square(Shape):
    square_list = []
    def __init__(self, s1):
        self.s1 = s1
        self.square_list.append(self)
    def calculate_perimeter(self):
        return self.s1 * 4
    def what_am_i(self):
        super().what_am_i()
        print("I am a Square.")

a_square = Square(29)
print(Square.square_list)
another_square = Square(93)
print(Square.square_list)

2.
class Shape():
    def what_am_i(self):
        print("I am a shape.")

class Square(Shape):
    square_list = []
    def __init__(self, s1):
        self.s1 = s1
        self.square_list.append(self)
    def calculate_perimeter(self):
        return self.s1 * 4
    def what_am_i(self):
        super().what_am_i()
        print("I am a Square.")
    def __repr__(self):
        return "{} by {} by {} by {}".format(self.s1, self.s1, self.s1, self.s1)
a_square = Square(29)
print(a_square)
 

3.
def compare(obj1, obj2):
    return obj1 is obj2
print(compare("a", "b"))

读书笔记之python深入面向对象编程

原文:https://www.cnblogs.com/JacquelineQA/p/12945060.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!