From entry to prison-object-oriented (2)


class Student:
    def __init__(self, name, tel, study_id='001', score=0):
        self.name = name
        self.tel = tel
        self.study_id = study_id
        self.score = score

    # 在打印一个对象的时候,系统会自动用这个对象去调用__repr__方法,并且获取这个方法的返回值
    # 返回值是什么就打印什么(返回值必须是字符串)
    def __repr__(self):
        return f'<{str(self.__dict__)[1:-1]}>'


#   __dict__将对象转换成字典
stu1 = Student('小王', 123456, '0001', 1)
stu2 = Student('小林', 22222, '0002', 12)
print(stu1)  # <'name': '小王', 'tel': 123456, 'study_id': '0001', 'score': 1>

# 对象属性的增删改查
# 查---获取对象的属性值
'''
对象.属性
getattr(对象,属性名) 可以做到动态获取属性值
'''
print(stu1.name)  # 小王

# value=input('请输入要获取的属性名:')
# print(getattr(stu2,value)) # value="name"  小林  value="tel" 22222
print(getattr(stu2, 'height', 180))  # 180 获取不存在的属性如果不给默认值会报错,

# 增/改
'''
对象.属性=值  属性存在的时候就是修改,属性不存在的时候就是增加
setattr(对象,属性名,值) 可以做到动态增加/修改属性值
'''
stu1.name = '我不是小王'
stu1.height = '新添加的属性:身高170'
print(stu1)  # <'name': '我不是小王', 'tel': 123456, 'study_id': '0001', 'score': 1, 'height': '新添加的属性:身高170'>
setattr(stu1, 'name', '我还是小王')
print(stu1)  # <'name': '我还是小王', 'tel': 123456, 'study_id': '0001', 'score': 1, 'height': '新添加的属性:身高170'>

# 删
'''
del 对象.属性   删除属性
del 对象       删除对象

delattr(对象,属性名)
'''
del stu1.height
print(stu1)  # <'name': '我还是小王', 'tel': 123456, 'study_id': '0001', 'score': 1>
delattr(stu1, 'study_id')
print(stu1)  # <'name': '我还是小王', 'tel': 123456, 'score': 1>

Object method:

Definition: Direct definition
Call: Object. Method name ()
Features: There is a default parameter self, this parameter does not need to be passed when calling, the system will automatically pass the current object to self for
use: If the function of the function requires an object , Then this function is defined as an object method

Class method:

Definition: Add @classmethod before defining the function
. Call: class.method name ()
Features: There is a default parameter cls. This parameter does not need to be passed when calling. The system will automatically pass the current class to cls for
use: if the function is implemented The function does not require the object to use the class, then the function is defined as a class method

Static method

Definition: Add @staticmethod before defining the function
. Call: Class. Method name ()
Features: No default parameters.
Use: Define static methods on the premise that the function does not require objects or classes.

class Student:
    # func1是对象方法
    def func1(self):
        print('对象方法')

    # func2是类方法
    @classmethod
    def func2(cls):
        print('cls:', cls)  # cls:<class '__main__.Student'>

    # 当前类能做的,cls都可以做

    # func3是静态方法
    @staticmethod
    def func3():
        print('静态方法')


print('Student:', Student)  # Student: <class '__main__.Student'>
class Person:
    """
    人类
    """
    num = 61

    def __init__(self, name='张三', age=18, gender='男'):
        self.name = name
        self.age = age
        self.gender = gender

    def eat(self, food='面条'):
        print(f'{self.name}在吃{food}')

    @classmethod
    def message(cls):
        print(f'人类目前的数量是:{cls.num}')

    @staticmethod
    def destroy():
        print('人类破坏环境')


p1 = Person()
# 类属性
'''
类名.__doc__    获取类的说明文档
print(Person.__doc__)    # 人类

类名.__module__  获取指定类所在的模块 如果结果是__main__  说明是当前模块
print(Person.__module__)  # __main__
print(list.__module__)  # builtins

对象.__class__   获取指定对象对应的类型,和type(对象)功能一样
print(p1.__class__)  # <class '__main__.Person'>
print(type(p1))  # <class '__main__.Person'>

类名.__name__    获取类名类型为str
print(Person.__name__) # 'Person'
print(int.__name__) # 'int'

类名.__dict__   获取类所有的字段和字段值,转化为字典,key是字段名,value是字段的值
print(Person.__dict__)
对象.__dict__   获取对象所有的属性和属性值,转化为字典,key是属性名,value是属性的值
print(p1.__dict__)  # {'name': '张三', 'age': 18, 'gender': '男'}

类名.__base__  获取指定类的父类
类名.__bases__ 获取类所有的父类
object是python中所有类的基类
print(Person.__base__)   # <class 'object'>
print(Person.__bases__)  # (<class 'object'>,)


'''

# 根据数据不同的类型创建以该类型名命名的文件
datas = ['abc', -0.1234, '你好', 564]
for data in datas:
    with open(rf'files\{data.__class__.__name__}.txt', 'a', encoding='utf-8') as f:
        f.write(str(data) + '\n')

getter

Usage: Before getting the object property, if you want to do something else, you can add a getter to this property.
Usage:
add _ before the property name that needs to add a getter and
define a function after the decorator @property, the function name is the property name removed _
The function has no parameters, but it needs a return value. The return value is the result of
getting the attribute value. When getting the attribute through the object, the attribute does not need to carry _

class Circle:
    pi = 3.14

    def __init__(self, r=10):
        self.r = r

    @property
    def area(self):
        return Circle.pi * self.r ** 2


c1 = Circle(100)
print(c1.area)

Exercise, add attributes to Person, requirement: age value is saved in age, but when getting age attribute, what you
get are: children (0-4), teenagers (5-12), youth (13-28), middle-aged (29-) 40) Middle-aged (41-55), elderly (over 55)

class Person:
    def __init__(self, age=0, name='张三', gender='男'):
        self.name = name
        self._age = age
        self.gender = gender

    @property
    def age(self):
        if 0 <= self._age <= 4:
            return '儿童'
        elif 5 <= self._age <= 12:
            return '少年'
        elif 13 <= self._age <= 28:
            return '青年'
        elif 29 <= self._age <= 40:
            return '中年'
        else:
            return '老年'

setter - must be added before adding getter
'
to do something else to object properties before the assignment, give this property to add setter
use
to define a function behind the decorator @ function name .setter, the function name is the property name to remove _
function and only A parameter (this parameter points to the value assigned during assignment)

 @age.setter
 def age(self, value):
     print(value)
     if type(value) != int:
         raise ValueError
     if value < 0 or value > 150:
         raise ValueError


p1 = Person()

# p1.age='dwa'  ValueError
# p1.age=151    ValueError

access permission

Public: Public properties and methods can be used inside and outside the class, and can be inherited.
Protected: Protected properties and methods can be used inside the class, but cannot be used outside, but
private ones can be inherited : private properties and methods. Methods can be used inside the class, cannot be used outside, and cannot be inherited

The attributes and methods in
python only have access rights: the so-called privatization of public python is just an explanatory hint

The method of privatization:
add __ in front of the attribute name and method name (can only start with two __, not end with __)

class Person:
    num = 100
    __info = '动物'

    def __init__(self, name='张三', age=18, gender='男'):
        self.name = name
        self.age = age
        self.gender = gender

    def func1(self):
        return Person.__info

    def __func2(self):
        return Person.num


p1 = Person()
print(p1.func1())  # 动物
print(Person.num)  # 100
# print(Person.__info) # AttributeError: type object 'Person' has no attribute '__info'
# print(p1.func2()) # AttributeError: 'Person' object has no attribute 'func2'
# print(Person._Person__info) # 动物 强行查看

Operator

When python uses operators, the essence is to call the method corresponding to the
operator. The method name of the method corresponding to each operator is fixed. Different types of data
will call the corresponding methods in different classes when participating in the same operation.

Whether a certain type of data supports a certain operation depends on whether there is a method corresponding to this operator in the type corresponding to the data

# __add__
class Person:
    def __init__(self, age=0, name='?', gender='男'):
        self.name = name
        self._age = age
        self.gender = gender
    #self指向+前面的数据,other指向+后面的数据
    def __add__(self, other):
        return self.name + other.name

    def __mul__(self, other):
        return [self.name for _ in range(len(other.name))]

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

    def __gt__(self, other1):
        return self._age>other1._age

p1 = Person(56,'王五','男')
p2 = Person(1, "小花",'女')
print(p1 + p2)  # 张三李四 本质是:pi.__add__(p2)
print(p1 * p2)  # ['张三', '张三'] 本质是:pi.__mul__(p2)

# 练习 根据年龄排序
p3=Person(20,'张三','男')
p4=Person(25,'老王','男')
# 方法一 重载 > 运算符
ps=[p1,p2,p3,p4]
print(sorted(ps))

# 方法二 实参高阶函数
ps.sort(key=lambda item :item._age)
print(ps)

Guess you like

Origin blog.csdn.net/weixin_44628421/article/details/109235545