有关类的一些知识

因为python 的类的情况比起C++简单了很多,这里就只说一下有些需要注意的事情

  • 私有与公有成员

    __init__  或者__xxx__  是系统特殊成员(前后两条下划线)
    _xxx 是保护成员(前面一条下划线)
    __xxx 是私有成员,不能通过实例来访问(前面两条下划线)
    调用私有成员是要使用装饰器 @property
    
  • 装饰器

    • 类方法 ( @classmethod )

      Python中允许声明属于类本身的方法,即类方法。不对特定实例进行操作,不能访问对象的实例变量,第一个参数必须是类对象本身,通常为cls,但在调用时不需要也不用给该函数传值

    • 静态方法 (@staticmethod)

      python 允许声明与类的对象实例无关的方法,称为静态方法,静态方法不对特定实例进行操作,在静态方法中访问对象实例会导致错误可通过类名访问也可通过对象的实例化

  • 继承和多态

    在继承中,子类要在括号内声明父类,父类的定义在子类其前面。在初始化过程中,子类不会自动调用父类的init

class Car:
    price = 30000  # 类变量

    def __init__(self, name):
        self.__name = name  # 成员私有变量
        self.color = ''

    def setcolor(self, color):
        self.color = color

    # 类方法
    @classmethod
    def getPrice(cls):
        print(cls.price)

    # 静态方法
    @staticmethod
    def setPrice(price):
        Car.price = price

    # 私有
    @property
    def name(self):
        return self.__name


class ECar(Car):
    def __init__(self, name):
        super().__init__(name)
        self.battery_size = 300

    def getEcar(self):
        print('我是电动车' + self.name + '电容' + str(self.battery_size))


a=Car('宝马')
b=ECar('奔驰')
# 类方法
a.getPrice()
# 静态方法
b.setPrice('10000')
b.getPrice()
a.getPrice()
# 私有
print(a.name)
b.getEcar()
posted @ 2020-09-19 17:44  life_if_forever  阅读(98)  评论(0)    收藏  举报