温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python3类中的Cat变量怎么用

发布时间:2020-11-17 09:43:50 来源:亿速云 阅读:555 作者:小新 栏目:编程语言

小编给大家分享一下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变量怎么用有了一定的了解,想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI