python3类中的Cat变量怎么用
小编给大家分享一下python3类中的Cat变量怎么用,希望大家阅读完这篇文章后大所收获,下面让我们一起去探讨吧!

在沙洋等地区,都构建了全面的区域性战略布局,加强发展的系统性、市场前瞻性、产品创新能力,以专注、极致的服务理念,为客户提供成都网站设计、网站建设 网站设计制作定制网站,公司网站建设,企业网站建设,品牌网站制作,成都全网营销推广,成都外贸网站制作,沙洋网站建设费用合理。
这里定义了Cat类和它的子类Blackcat,主要说明两个主题:私人属性、方法的继承与覆盖
私人属性的使用是受到一定限制的,这里主要说明在哪些地方可以用,哪些地方不能调用
因为子类继承父类时,会将父类的所有方法都继承过来,但是如果在子类中定义了一个和父类同名的方法,则会将父类的方法覆盖下去,__init__也是如此
定义类
class Cat(Animal):
def __init__(self, weight): # 覆盖了父类的__init__,所以定义实例时不需要指定name和age
self.__weight = weight
self._weight = weight + 1
self.weight = self._weight + 1
def get_myweight(self):
print("My weight is", self._weight, "kg")
def get_trueweight(self):
print("Actually the cat's weight is",self.__weight)
@staticmethod
def print_cat():
print("这个类是Animal类的子类,也是Blackcat类的父类")
print("Cat类和Blackcat类结合,主要用于讲解私人属性、方法的继承与覆盖")
print("weight是普通属性,可以在外部访问,即用类调用属性获得,可以被子类内部调用")
print("_weight这样前面加一个下划线表示希望你不要在外部访问它,但是还是可以访问的,可以被子类内部调用")
print("__weight这样加两个下划线的是不允许外部访问的,只可以在类中被调用,不可以被子类内部调用")
print("__init__在子类中定义则覆盖了父类中的__init__,不需要指定父类中的属性,也无法调用父类的属性")
print("在子类中实现和父类同名的方法,也会把父类的方法覆盖掉")
class Blackcat(Cat):
def get_weight(self):
print("My weight is", self.weight)
def get_weight_again(self): # 可以
print("Actuall my weight is", self._weight)
def get_true_weight(self): # 这个方法因为无法调用self.__weight所以这个方法无法使用
print("My weight is exactly", self.__weight)
def get_trueweight(self): # 覆盖了Cat父类中定义的方法
print("My weight is exactly", self._weight+1)创建实例
# 测试私人变量的外部访问 cole = Cat(5) cole.weight # 7 cole._weight # 6 cole.get_trueweight() # 在类中引用__weight,用这个方法返回 # Actually the cat's weight is 5 cole._Cat__weight # 非要访问也可以,其实是python解释器把__weight改成了_Cat__weight # 5 # 测试私人变量的子类调用 cain = Blackcat(5) cain.get_weight() # My weight is 7 cain.get_weight_again() # Actuall my weight is 6 # cain.get_true_weight() # 报错 # 测试方法的继承与覆盖 cain.get_myweight() # # My weight is 6 kg cain.get_trueweight() # 子类中同名函数覆盖父类 # My weight is exactly 7
看完了这篇文章,相信你对python3类中的Cat变量怎么用有了一定的了解,想了解更多相关知识,欢迎关注创新互联行业资讯频道,感谢各位的阅读!
文章名称:python3类中的Cat变量怎么用
网址分享:http://www.jxjierui.cn/article/pioogs.html


咨询
建站咨询
