如何在 Python 中定义一个类? [英] How can I define a class in Python?
本文介绍了如何在 Python 中定义一个类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
很简单,我正在学习 Python,我找不到告诉我如何编写以下内容的参考:
Quite simple, I'm learning Python, and I can't find a reference that tells me how to write the following:
public class Team {
private String name;
private String logo;
private int members;
public Team(){}
// Getters/setters
}
后来:
Team team = new Team();
team.setName("Oscar");
team.setLogo("http://....");
team.setMembers(10);
这是一个具有属性的类团队:名称/徽标/成员
That is a class Team with the properties: name/logo/members
编辑
经过几次尝试后,我得到了这个:
After a few attempts I got this:
class Team:
pass
稍后
team = Team()
team.name = "Oscar"
team.logo = "http://..."
team.members = 10
这是 Python 的方式吗?感觉很奇怪(当然来自强类型语言).
Is this the Python way? It feels odd (coming from a strongly typed language of course).
推荐答案
class Team:
def __init__(self):
self.name = None
self.logo = None
self.members = 0
在 Python 中,您通常不会编写 getter 和 setter,除非您确实对它们有重要的实现(此时您使用属性描述符).
In Python, you typically don't write getters and setters, unless you really have a non-trivial implementation for them (at which point you use property descriptors).
这篇关于如何在 Python 中定义一个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文