'''
笔记(类的进阶)
昨天知识点
类的三要素: 类名 属性(变量 ) 方法 (函数)
构造方法 魔法方法 __init__ __del__
1. 继承(object)基类 祖宗类
1.1 继承可以增加多个属性 也可以修改属性 但是不能少属性
1.2 子类可以重新写init方法
1.3 __bases__查看父类是谁
1.4 可以完全继承,部分继承 (自己增加属性) 完全不继承(都是自己写)
方法1: 类名.方法(self) 方法2: super().方法()
2. 多继承(c查看顺序:mro(),官方推荐使用super方法继承:super())
2.1 多继承就是先找最左边的继承,再找不到就找object
3. 魔法方法(可以重写)
3.1 阔方法:__call__直接实例调用
3.2 str reper 两个魔法方法
题外
# 此py文件导入到别的文件中去下面文件不会运行
if __name__ == "__main__":
area = Square(10, 10)
area.square()
'''
# 1. 继承
# 1.1第一部分
# l = int(input("请输入矩形长度:"))
# w = int(input("请输入矩形宽度:"))
# class Rectangle(object): #父类
# def __init__(self, long, wide):
# self.long = long
# self.wide = wide
#
# def func1(self):
# # "{}{}".format(self.long, self.wide)
# print("面积为:", self.long * self.wide)
#
#
# # class Rectangle2(Rectangle): # 继承
# # pass
#
# # 正方形
# class Rectangle2(Rectangle): # 继承
# def __init__(self, long, wide):
# if long == wide:
# Rectangle.__init__(self, long, wide) # 调用父类的初始化方法
# else:
# print("这是正方形") # 但是还会报错
#
#
# area = Rectangle2(10, 10)
# area.func1()
# 1.2 第二部分
# class Dog:
# def __init__(self):
# print("汪汪汪")
#
#
# class God_Dog(Dog):
# def __init__(self): # 子类重写了init方法
# Dog.__init__(self) # 调用父类属性
# print("旺旺旺") # 增加属性
#
#
# gg = God_Dog()
# # __bases__查看父类是谁
# # print(Dog.__bases__)
# # print(God_Dog.__bases__)
#
# ————————————————————————————————————————————————————————————
# 2. 多继承
# 2.1 第一部分
# class Base:
# def play(self):
# print("类的祖宗")
#
#
# class A(Base):
# def play(self):
# print("类祖宗的儿子")
#
#
# class B(Base):
# def play(self):
# print("类祖宗的女儿")
#
#
# class C(A, B):
# pass
#
#
# jc = C() # 按顺序
# jc.play() # 这里先找AB,AB找不到就找object
# 3.魔法方法
# 3.1第一部分str repr
# 1. add
# 2. call
# class Str_Repr:
# def __str__(self):
# return "str魔法方法"
#
# def __repr__(self):
# return "repr魔法方法"
#
#
# S_R = Str_Repr()
# print(S_R)
# S_R()
# class Str:
# def __str__(self):
# return "str魔法方法"
#
#
# class Repr:
# def __repr__(self):
#
# return "repr魔法方法"
# S =Str()
# R = Repr()
# print(S,R)
# 作业:在之前的基础上,定义正方形类。实现实例的直接调用,调用时打印变成,同事直接打印实例时能够打印出实例面积
class Rectangle:
def __init__(self, long, wide):
self.long = long
self.wide = wide
def func1(self):
return "面积为:{}".format(self.long * self.wide)
class Square(Rectangle):
def square(self):
if self.long == self.wide:
super(Square, self).func1()
else:
print("警告:这是正方形,请输入正确的边长!")
def __call__(self, *args, **kwargs):
print('正方形边长为:{}'.format(self.long))
# def __str__(self):
# return self.func1()
def __repr__(self):
return self.func1()
area = Square(10, 10)
area()
# area
print(area)
# area.__repr__()
# area.square()
# area.func1()
# # 此py文件导入到别的文件中去下面文件不会运行
# if __name__ == "__main__":
# area = Square(10, 10)
# area.square()
python继承多继承魔法方法
猜你喜欢
转载自blog.csdn.net/weixin_44961387/article/details/100566475
今日推荐
周排行