python中也有类的概念。Python中的类是面向对象编程(OOP)的核心概念之一,用于描述具有相同属性和方法的对象的集合。类定义了一组相关的属性和方法,用于创建具有特定特征和行为的具体对象,那么和Java中的类应该差不多,python中的类也有封装,继承、多态。完成python中类的练习,基本就能实现实体业务的逻辑。
马上动手练习
# Clase en vídeo: https://youtu.be/Kp4Mvapo5kc?t=29327
### Classes ###
# Definición
class MyEmptyPerson:
pass # Para poder dejar la clase vacía
print(MyEmptyPerson)
print(MyEmptyPerson())
# Clase con constructor, funciones y popiedades privadas y públicas
class Person:
def __init__(self, name, surname, alias="Sin alias"):
self.full_name = f"{name} {surname} ({alias})" # Propiedad pública
self.__name = name # Propiedad privada
def get_name(self):
return self.__name
def walk(self):
print(f"{self.full_name} está caminando")
my_person = Person("Brais", "Moure")
print(my_person.full_name)
print(my_person.get_name())
my_person.walk()
my_other_person = Person("Brais", "Moure", "MoureDev")
print(my_other_person.full_name)
my_other_person.walk()
my_other_person.full_name = "Héctor de León (El loco de los perros)"
print(my_other_person.full_name)
my_other_person.full_name = 666
print(my_other_person.full_name)
运行代码看看结果:
根据结果分析代码
#定义一个类MyEmptyPerson 用class修饰
class MyEmptyPerson: pass # Para poder dejar la clase vacía #打印类的信息 print(MyEmptyPerson) print(MyEmptyPerson())
#定义一个人类
class Person: #构造函数,带属性 def __init__(self, name, surname, alias="Sin alias"): self.full_name = f"{name} {surname} ({alias})" # Propiedad pública self.__name = name # Propiedad privada #函数 def get_name(self): return self.__name #函数 def walk(self): print(f"{self.full_name} está caminando")
#创建类的对象,并调用类的属性函数
my_person = Person("Brais", "Moure") print(my_person.full_name) print(my_person.get_name()) my_person.walk()
看来也很简单呀