As a newbie who has just started Python, I don’t understand the concept of classes. When should I define a class and what is the role of this class? After reading a lot of books and web pages, I can summarize it as follows:
##Class (class): class is a classification of a class in real life. An abstraction of things with common characteristics, used to describe a collection of objects with the same properties and methods.
Reference code: (Recommended learning: Python video tutorial)
# 定义“人”类 class Person(object): class_name = "人类" #初始化时需要给“人”分配一个名字name # 工作时长 working_time则留给“男人”和“女人”去分开定义 def __init__(self, name): self.name = name self.working_time = None #定义一个方法,它能输出工作时长 def work(self): print(self.working_time) #还可以定义其他方法 # 定义“男人”类, 它需要“继承”“人”类 class Man(Person): def __init__(self, name): # 调用“人”类的初始化方法以完成继承 Person.__init__(self, name) # 定义工作时长 self.working_time = 8 # 定义“女人”类,它需要“继承”“人”类 class Woman(Person): def __init__(self, name): # 调用“人”类的初始化方法以完成继承 Person.__init__(self, name) # 定义工作时长 self.working_time = 6 print(Person.class_name) # 输出 人类 zhangsan = Man("zhangsan") print(zhangsan.working_time) # 输出 8 Lisi = Woman("Lisi") print(Lisi.working_time) # 输出 6
Python Tutorial column to learn!
The above is the detailed content of How to understand python classes. For more information, please follow other related articles on the PHP Chinese website!