Python高级学习第二课 2022-01-07

一,面向对象

super() 在子类中调用父类的方法进行使用

类属性与方法

类的私有属性

__private_attrs:两个下划线开头,声明该属性为私有,不能在类的外部被使用或直接访问。在类内部的方法中使用时 self.__private_attrs

类的方法

在类的内部,使用 def 关键字可以为类定义一个方法,与一般函数定义不同,类方法必须包含参数 self,且为第一个参数

类的私有方法

__private_method:两个下划线开头,声明该方法为私有方法,不能在类的外部调用。在类的内部调用 self.__private_methods

class Cat:
    __secretCount = 0  # 私有变量
    publicCount = 0  # 公开变量

    def count(self):
        self.__secretCount += 1
        self.publicCount += 1
        print(self.__secretCount)

counter = Cat()
counter.count()
print(counter.publicCount)
print(counter.__secretCount) # 报错,实例不能访问私有变量

获取私有变量 

class Cat:
    __secretCount = 0  # 私有变量
    publicCount = 0  # 公开变量

    def count(self):
        self.__secretCount += 1
        self.publicCount += 1
        print(self.__secretCount)

    def secretCount(self):
        return self.__secretCount

counter = Cat()
counter.count()
print(counter.publicCount)

print(counter.secretCount()) # 不报错

 动态给实例添加属性和方法

from types import MethodType

#创建一个类
class Cat(object):
    def __init__(self,name,):
        self.name = name
    
per = Cat("Lucy")

per.name = "Tom"

def say(self):
    print("Its name is "+self.name)

per.speak = MethodType(say,per)
per.speak()

限制动态添加

__slots__ = ("属性1",“属性2”,...)

除了这些括号中的属性以外的其他属性都不能被添加。

运算符重载

object.__add__(self, other)#加法运算
object.__sub__(self, other)#减法运算
object.__mul__(self, other)#乘法运算

 一个例子

class Vector:#创建一个类
    def __init__(self,a):
        self.a = a
    def __str__(self):
        return 'Vector (%d)' % (self.a)
    #运算符重载
    def __add__(self, other):#做加法运算
        return Vector(self.a + other.a)
    def __pow__(self, other):#做平方运算
        return Vector(self.a * other.a)

v1 = Vector(9)
v2 = Vector(5)
print(v1 + v2)#做加法运算
print(v1.__pow__(v2))#做平方运算

property() 函数

property() 函数的作用是在新式类中返回属性值。

class property([fget[, fset[, fdel[, doc]]]])

参数

  • fget -- 获取属性值的函数
  • fset -- 设置属性值的函数
  • fdel -- 删除属性值函数
  • doc -- 属性描述信息
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值