当前分类:python>>正文

Python编程中的对象和实用方法

来源:互联网   更新时间:2023年8月20日  

Python 笔记

一、类和对象

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

p = Person("Tom", 20)

二、继承和多态

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

    def eat(self):
        print("I can eat.")

class Dog(Animal):
    def __init__(self, name):
        super().__init__(name)

    def bark(self):
        print("I can bark.")

class Cat(Animal):
    def __init__(self, name):
        super().__init__(name)

    def meow(self):
        print("I can meow.")

d = Dog("Doggy")
d.eat()  # 输出“I can eat.”
d.bark()  # 输出“I can bark.”

c = Cat("Kitty")
c.eat()  # 输出“I can eat.”
c.meow()  # 输出“I can meow.”

三、装饰器

def my_decorator(func):
    def wrapper():
        print("Before the function is called.")
        func()
        print("After the function is called.")
    return wrapper

@my_decorator
def say_hello():
    print("Hello World!")

say_hello()

四、lambda表达式

arr = [(1, 2), (3, 4), (5, 6)]
arr.sort(key=lambda x: x[0])
print(arr)  # 输出[(1, 2), (3, 4), (5, 6)]

总结

本文固定链接:https://6yhj.com/leku-p-5482.html  版权所有,转载请保留本地址!
[猜你喜欢]

标签: Tkinter示例