类与函数 [英] Classes vs. Functions

查看:59
本文介绍了类与函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

即使对于没有任何编程经验但具有一定数学背景的人来说,函数也很容易理解.另一方面,类似乎更难掌握.

Functions are easy to understand even for someone without any programming experience, but with a fair math background. On the other hand, classes seem to be more difficult to grasp.

假设我要创建一个类/函数,计算给定生日和当前年份的人的年龄.我应该为此创建一个类还是一个函数? 还是选择取决于场景?

Let's say I want to make a class/function that calculates the age of a person given his/her birthday year and the current year. Should I create a class for this, or a function? Or is the choice dependant to the scenario?

P.S.我正在使用Python,但是我想这个问题很普遍.

P.S. I am working on Python, but I guess the question is generic.

推荐答案

创建一个函数.函数特定的事物,类特定的事物.

Create a function. Functions do specific things, classes are specific things.

类通常具有方法,这些方法是与特定类相关联的函数,并且执行与该类所具有的事物相关联的事情-但是,如果您只想做某事,那么功能就是您所需要的.

Classes often have methods, which are functions that are associated with a particular class, and do things associated with the thing that the class is - but if all you want is to do something, a function is all you need.

从本质上讲,类是将函数(作为方法)和数据(作为属性)分组为围绕某种事物的逻辑单元的一种方式.如果您不需要该分组,则无需进行授课.

Essentially, a class is a way of grouping functions (as methods) and data (as properties) into a logical unit revolving around a certain kind of thing. If you don't need that grouping, there's no need to make a class.

这篇关于类与函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆