类和对象(二)

2018-11-22  本文已影响0人  憧憬001

一、类方法和静态方法

class Person:

    def __init__(self, name):
        self.name = name

    def eat(self, food):
        print("%s在吃%s" %(self.name, food))


    @classmethod
    def destory(cls):
        print("人类破坏环境")
        print(cls)
        # 可以用cls创建对象
        p1 = cls("小李")
        p1.eat("大餐")
    @staticmethod
    def animal():
        print("动物世界")

Person.destory()
print(Person)
Person.animal()
>>>>
人类破坏环境
<class '__main__.Person'>
小李在吃大餐
<class '__main__.Person'>
动物世界

对象方法:当实现函数的功能需要使用到对象的属性的时候

类方法:实现函数的功能不需要对象的属性,但是需要类的时候

静态方法:实现函数的功能不需要对象的属性,也不需要类的时候


# 练习:数学类  属性:pi   求两个数的和, 求一个圆的面积

import math

class Math:
    pi = math.pi

    @staticmethod
    def sum_num(*args):
        return sum(args)

    @classmethod
    def eara(cls, r):
        return cls.pi*r**2


print("和:", Math.sum_num(5, 8))
print("面积:", Math.eara(5))
>>>>
和: 13
面积: 78.53981633974483

二、私有化

class Person:

    num = 66

    def __init__(self):
        self.__name = "小李"

    def show_message(self):
        print("名字:%s" % self.__name)


p1 = Person()

print(p1._Person__name)
>>>>
小李

三、对象属性的getter和setter方法

2.给对象属性添加getter
a.属性命名的时候,属性名前加_; 例如:self._age = 0
b.声明一个函数,函数的名字是属性名(不要下划线),不需要额外参数,有返回值;并且函数前使用@property修饰。
这个函数的返回值就是获取属性的结果
例如:
@property
def age(self):
return 年龄相关值

c.当需要获取属性的时候通过对象.不带下划线的属性;例如:对象.age

3.给对象属性添加setter
想要给对象属性添加setter,必须先给它添加getter
a.属性命名的时候,属性名前加_; 例如:self._age = 0
b.声明一个函数,函数的名字是属性名(不要下划线),需要一个额外的参数,不用返回值;
并且函数前使用@getter名.setter修饰
例如:
@age.setter
def age(self, value):
self._age = value

c.当需要给属性赋值的时候,通过对象.不带下划线的属性来赋值;例如: 对象.age = 100

class Person:
    def __init__(self, name = "小王"):
        self.name = name
        self._age = 5
        self.gender = "男"

    @property
    def age(self):
        if self._age < 1:
            return "婴儿"
        elif self._age < 18:
            return "未成年"
        elif self._age < 60:
            return "壮年"
        elif self._age < 199:
            return "大爷"
        else:
            return "神仙"
    @age.setter
    def age(self, value):
        if not isinstance(value, int):
            print("年龄必须是整数")
            raise ValueError
        if not (0 <= value <= 200):
            print("年龄超出范围")

        self._age = value




p1 = Person()
print(p1.age)
p1._age = 100
print(p1.age)

# 赋值
p1.age = 200
print(p1.age)
>>>>
未成年
大爷
神仙

四、类的继承

class Person(object):
    num = 61

    # 注意:__slots__对应的值不会被继承
    __slots__ = ('name', 'age', 'sex')

    def __init__(self):
        self.name = '张三'
        self.age = 0
        self.sex = '男'

    def show_message(self):
        print('%s你好吗?' % self.name)


# Student类继承自Person类
class Student(Person):
    pass


# 创建学生对象
stu1 = Student()
# 对象属性可以继承
print(stu1.name, stu1.age, stu1.sex)

# 类的字段可以继承
print(Student.num)

# 对象方法可以继承
stu1.show_message()



p1 = Person()
# p1.color = '黄色'
stu1.color = '白色'
print(stu1.color)
>>>>
张三 0 男
61
张三你好吗?
白色

五、子类添加属性和方法

1.在子类中添加方法
class Person:
    # 类的字段
    num = 61

    # 对象属性
    def __init__(self):
        self.name = '张三'
        self.age = 0
        self.sex = '男'

    def fun1(self):
        print('Person的对象方法')

    # 方法
    def show_message(self):
        print('%s,你好吗?' % self.name)

    @staticmethod
    def info():
        print('我是人类')


class Student(Person):

    def study(self):
        print('%s在学生' % self.name)

    @classmethod
    def message(cls):
        super().info()
        print('我是学生!')

    # 完全重写
    @staticmethod
    def info():
        print('我是学生!!!')

    # 保留父类的功能
    def show_message(self):
        super().show_message()
        print('我去上学~')
        super().fun1()
2.添加属性
class Person:
    num = 61

    def __init__(self, name):
        self.name = name
        self.age = 0


class Student(Person):
    number = 100

    def __init__(self, name):
        super().__init__(name)
        self.study_id = '001'


print(Student.number, Student.num)

stu1 = Student('小明')
print(stu1.name, stu1.age, stu1.study_id)

# 练习:
# 声明一个动物类,有属性:年龄,颜色,类型。
#  要求创建动物对象的时候类型和颜色必须赋值,年龄可以赋值也可以不赋值
# 声明一个猫类,有属性:年龄,颜色,类型, 爱好
# 要求创建猫对象的时候,颜色必须赋值,年龄和爱好可以赋值也可以不赋值,类型不能赋值


class Aniaml:
    def __init__(self, type, color, age=0):
        self.type = type
        self.color = color
        self.age = age


class Cat(Aniaml):
    def __init__(self, color, age=0, hobby=''):
        super().__init__('猫科', color, age)
        self.hobby = hobby


an1 = Aniaml('犬科', '黄色')
an2 = Aniaml('犬科', '黄色', 10)

cat1 = Cat('白色')
cat2 = Cat('灰色', 3)
cat3 = Cat('灰色', hobby='睡觉')
cat4 = Cat('灰色', 3, '睡觉')
>>>>
100 61
小明 0 001

六、多继承

class Animal:
    num = 61

    def __init__(self, name='名字', age=0, color=''):
        self.name = name
        self.age = age
        self.color = color

    def show_info(self):
        print('=====')
        # print('名字:%s 年龄:%d 颜色:%s' % (self.name, self.age, self.color))


class Fly:
    info = '飞'

    def __init__(self, distance=0, speed=0):
        self.distance = distance
        self.speed = speed

    @staticmethod
    def show():
        print('会飞!')


# 让Birds同时继承Animal和Fly
class Birds(Fly, Animal):
    pass


bird1 = Birds()
# 对象属性只能继承第一个类的对象属性
print(bird1.speed)

# 两个类的字段都能继承
print(Birds.num, Birds.info)

# 两个类的方法都能继承
Birds.show()
bird1.show_info()
>>>>
0
61 飞
会飞!
=====

封装:可以对多条数据(属性)和多个功能(方法)进行封装
继承:可以让一个类拥有另外一个类的属性和方法
多态:有继承就有多态(一个事物的多种形态)

七、运算符重载

"""
1.别的语言的函数和函数的重载
C++/java声明函数的语法:
返回值类型 函数名(参数类型1 参数名1, 参数类型2 参数名2){
    函数体
}

int func1(){
    
}
void func1(int a){

}

void func1(char a){

}
int func1(int a, int b){

    
}

上面这4个函数是不同的函数(可以同时存在)


python中的函数不支持重载
def func1():
    pass
    
def func1(a):
    pass
    
def func1(a, b)
    pass
    
最终只保留最后这一个func1,前面的会被覆盖


2.运算符重载
python中使用运算的时候,实质是在调用相应的魔法方法。(python中每个运算符都对应一个魔法方法)
运算符重载:在不同的类中实现同一个运算符对应的魔法方法,来让类的对象支持相应的运算
"""


class Student(object):
    def __init__(self, name='', score=0, age=0):
        self.name = name
        self.score = score
        self.age = age

    #  + 重载
    """
    数据1 + 数据2 -- 数据1会传给self, 数据2会传给other
    """
    def __add__(self, other):
        # self + other
        return self.score + other.score

    # - 运算
    def __sub__(self, other):
        # self - other
        return self.age - other.age

    # 注意:>和<一般情况下只需要重载一个,另外一个自动支持
    # < 运算
    def __lt__(self, other):
        return self.score < other.score

    #  > 运算
    def __gt__(self, other):
        return self.age > other.age

    def __repr__(self):
        return '<'+(str(self.__dict__)[1:-1])+'>'


stu1 = Student('小花', 90, 16)
stu2 = Student('小明', 80, 18)
stu3 = Student('小红', 87, 23)
stu4 = Student('小🐶', 30, 15)
print(stu1 + stu2)

print(stu1 - stu2)

all_students = [stu1, stu2, stu3, stu4]
all_students.sort()


print(all_students)

print(max(all_students))
>>>>
170
-2
[<'name': '小🐶', 'score': 30, 'age': 15>, <'name': '小明', 'score': 80, 'age': 18>, <'name': '小红', 'score': 87, 'age': 23>, <'name': '小花', 'score': 90, 'age': 16>]
<'name': '小红', 'score': 87, 'age': 23>

八、内存管理机制

# 2.减少引用计数
"""
a. 删除引用
b. 让当前对象的引用成为别的对象的引用
"""
print(id(list3[1]))
del list3[0]
print(getrefcount(list1))


list2 = 100
print(id(list2))
print(getrefcount(list1))

list3 = 100
print(id(list3))

print(getrefcount(100))
>>>>
2
3
4
1815509104
3
1815509104
2
1815509104
13
上一篇 下一篇

猜你喜欢

热点阅读