Python Notes 01 (Variables and Object-Oriented Programming)

1. The use of args and kwargs

Note that args is a * and kwargs is a **.

def func_1(a, b):
    print(f'a:{a}, b:{b}')


def func_2(*args):   # args: 个数可变的位置传参
    print(f'args:{args}')


def func_3(a=100, **kwargs):   # kwargs 是个数可变的关键字参数
    print(f'a:{a}, kwargs:{kwargs}')


func_1(1, 2)
func_2(1, 2)
func_3(1)  # a:1, kwargs:{}
func_3(10, x=1000, y=2002)   # a:10, kwargs:{'x': 1000, 'y': 2002}

Scope of two variables

1 The internal variables of the function are local variables, and the external variables are global variables.

2 You can use global to globalize internal variables of functions

Three object-oriented programming

1 Object-oriented, focusing on process

2 Make the function body unchanged and the parameters variable

3 Put the elephant in the refrigerator using an object-oriented approach

3.1 Object-oriented design of animal objects

# 把大象装进冰箱
class Animal:
    def __init__(self, name):
        self.name = name

    def enter(self):
        print(f'{self.name} 走进冰箱')


class Fridge:
    def open(self):
        print(f'冰箱门打开')

    def close(self):
        print('关上冰箱门')


# 使用方法创建对象
fridge = Fridge()   # 创建冰箱对象
elephant = Animal('大象')
fridge.open()
elephant.enter()
fridge.close()

3.2 Object-oriented design phone object

class Phone():  # 可写可不写括号,有继承必须写+
    # init传入的变量只在init生效  brand, goods_name, goods_no, weight, place, color
    def __init__(self, brand, goods_name, goods_no, weight, place, color):  # 局部变量
        self.brand = brand
        self.goods_name = goods_name
        self.goods_no = goods_no
        self.weight = weight
        self.place = place
        self.color = color

    def info(self):  # 手机行为
        print(f'品牌:{self.brand}')
        print(f'商品名称:{self.goods_name}')
        print(f'商品编号:{self.goods_no}')
        print(f'机身重量:{self.weight}')
        print(f'商品产地:{self.place}')
        print(f'机身颜色:{self.color}')

    def call(self, name):  # name是方法的形式参数
        print(f'我使用{self.brand}正在给{name}打电话')


# 创建对象
huawei = Phone('honor', 'x40', '1004', '0.5kg', 'china', 'blue')   # 位置传参
huawei.info()
huawei.call('mother')

print('__________________________________________________')
meizu = Phone('meizu', '50', '2004', '0.6kg', 'china', 'blue')   # 位置传参
meizu.info()
meizu.call('mother')

print('__________________________________________________')
# 单独绑定属性
meizu.ipv6 = '支持IPV6'
print('查看单独绑定的属性:', meizu.ipv6)

3.3 Methods of dynamically binding objects

# 绑定方法
def send_message(content):
    print(f'发送短信,内容为:', content)

meizu.send_message = send_message  # 赋值不加括号,调用加括号
meizu.send_message('今天天气不错!!!')
print('查看内存位置:', id(send_message))
print('查看对象内存位置:', id(meizu.send_message))

3.4 Use of property

propertyIt is a built-in decorator in Python, used to turn a class method into a property. Its main function is to allow you to perform some specific operations when accessing the properties of a class, such as getting, setting, deleting, etc., and using it just like accessing ordinary properties. This helps encapsulate the internal implementation details of the class while providing more control and security.

class MyClass:
    def __init__(self, value):
        self._value = value  # 带下划线的属性通常被认为是私有属性

    @property
    def value(self):
        # 在访问属性时执行的代码
        return self._value

    @value.setter
    def value(self, new_value):
        # 在设置属性时执行的代码
        if new_value < 0:
            raise ValueError("Value must be non-negative")
        self._value = new_value

    @value.deleter
    def value(self):
        # 在删除属性时执行的代码
        print("Deleting value")
        del self._value

# 创建对象
obj = MyClass(42)

# 获取属性值
print(obj.value)  # 输出: 42

# 设置属性值
obj.value = 55

# 删除属性值
del obj.value

The benefit of using propertya decorator is that it allows you to hide how a property is actually stored, making it easier to modify the property's internal implementation without affecting external code. It also allows you to add custom validation logic to ensure the properties are valid.

Guess you like

Origin blog.csdn.net/March_A/article/details/133243314