python类入门

In computer programming, classes are a convenient way to organize data and functions such that they are easy to reuse and extend later. In this post, we will walk through how to build a basic class in python. Specifically, we will discuss the example of implementing a class that represents instagram users.

在计算机程序设计中,类是组织数据和功能的便捷方法,以便易于重用和扩展。 在本文中,我们将逐步介绍如何在python中构建基本类。 具体来说,我们将讨论实现代表instagram用户的类的示例。

Let’s get started!

让我们开始吧!

To start, let’s define a simple class that represents Instagram Users. Initially we won’t include any data (attributes) or functions (methods):

首先,让我们定义一个代表Instagram用户的简单类。 最初,我们将不包含任何数据(属性)或函数(方法):

class Instagram_User:
pass

Two import concepts to understand in object-oriented program are classes and class instances. A user of the Instagram platform can be considered an instance of the ‘Instagram_User’ class. The distinction here is that the ‘Instagram_User’ class serves as a blueprint for creating Instagram users, and an instance of the ‘Instagram_User’ class may refer to a specific user. To see this, we can define two Instagram user instances, insta_user_1 and insta_user_2:

类和类实例是在面向对象程序中要理解的两个导入概念。 Instagram平台的用户可以视为'Instagram_User'类的实例。 此处的区别在于'Instagram_User'类充当创建Instagram用户的蓝图,并且'Instagram_User'类的实例可以引用特定用户。 为此,我们可以定义两个Instagram用户实例insta_user_1和insta_user_2:

insta_user_1 = Instagram_User()
insta_user_2 = Instagram_User()

Each of these users will be their own unique instances of the Instagram_User class. We can print both objects:

这些用户中的每一个都是Instagram_User类的自己的唯一实例。 我们可以打印两个对象:

print("User Object 1: ", insta_user_1)
print("User Object 2: ", insta_user_2)
Image for post

Here we can see that each object has a unique memory address. Next thing we can do is create variables for each instance. Let’s define instance variables that holds the user name of each user:

在这里我们可以看到每个对象都有一个唯一的内存地址。 接下来,我们可以为每个实例创建变量。 让我们定义实例变量来保存每个用户的用户名:

insta_user_1.user_name = 'nychef100'
insta_user_2.user_name = 'worldtraveler123'

We can also define the name of each user:

我们还可以定义每个用户的名称:

insta_user_1.name = 'Jake Cohen'
insta_user_2.name = 'Maria Lopez'

the email address:

电子邮件地址:

insta_user_1.email = 'jcohen100@gmail.com'
insta_user_2.email = 'mlopez123@gmail.com'

Finally let’s define an instance variable that tells us whether or not each user has a private account:

最后,让我们定义一个实例变量,该变量告诉我们每个用户是否都有私人帐户:

insta_user_1.private = True
insta_user_2.private = False

Now each instance has attribute values unique to each user. Let’s print the user names:

现在,每个实例都具有每个用户唯一的属性值。 让我们打印用户名:

print(insta_user_1.user_name)
print(insta_user_2.user_name)
Image for post

Ideally, we’d like to set all of this information for each user automatically, instead of setting these values manually. To get the full benefit of classes, we should define a method that allows us to initialize each user instance with the values we defined manually. The initialization method, which is basically a constructor, is going to be called ‘__init__’:

理想情况下,我们希望为每个用户自动设置所有这些信息,而不是手动设置这些值。 为了获得类的全部好处,我们应该定义一个方法,该方法允许我们使用我们手动定义的值来初始化每个用户实例。 初始化方法基本上是构造函数,将被称为'__init__':

class Instagram_User:
def __init__(self, user_name, name, email, private):
self.user_name = user_name
self.name = name
self.email = email
self.private = private

Here, the ‘self’ parameter is the instance and is what will allows us to share attribute information within the instance. For example, when we write:

在这里,“ self”参数是实例,它是允许我们在实例内共享属性信息的参数。 例如,当我们写:

insta_user_1 = Instagram_User('nychef100', 'Jake Cohen', 'jcohen100@gmail.com', True)
insta_user_2 = Instagram_User('worldtraveler123', 'Maria Lopez', 'mlopez123@gmail.com', False)

the ‘self’ parameters in each case are the insta_user_1 and insta_user_2 objects respectively. If we print the emails we see:

在每种情况下,“ self”参数分别是insta_user_1和insta_user_2对象。 如果我们打印电子邮件,我们将看到:

print(insta_user_1.email)
print(insta_user_2.email)
Image for post

This allows us to define attributes with significantly less code than when we defined them manually. Now suppose we’d like to perform some operation on the attributes of each user. For example, we can define a method that tells us whether or not a user has a private account. In our method, we print “User has a Private Account”, if ‘self.private’ is True, otherwise, we print “User has a Public Account”:

与手动定义属性相比,这使我们可以用更少的代码来定义属性。 现在假设我们想对每个用户的属性执行一些操作。 例如,我们可以定义一个方法来告诉我们用户是否具有私人帐户。 在我们的方法中,如果“ self.private”为True,则打印“用户具有私人帐户”;否则,我们打印“用户具有公共帐户”:

def isPrivate(self):
if self.private:
print("{} has a Private Account".format(self.name))
else:
print("{} has a Public Account".format(self.name))

The full script should look as follows:

完整的脚本应如下所示:

class Instagram_User:
def __init__(self, user_name, name, email, private):
self.user_name = user_name
self.name = name
self.email = email
self.private = private
def isPrivate(self):
if self.private:
print("{} has a Private Account".format(self.name))
else:
print("{} has a Public Account".format(self.name))

Let’s call the method using the insta_user_1 instance:

让我们使用insta_user_1实例调用该方法:

insta_user_1.isPrivate()
Image for post

And on insta_user_2:

在insta_user_2上:

insta_user_2.isPrivate()
Image for post

As you can see, since the ‘self’ parameter is passed to ‘__init__’ and ‘isPrivate’, upon initialization the ‘isPrivate’ method has full access to the attributes of the corresponding instance.

如您所见,由于将“ self”参数传递给“ __init__”和“ isPrivate”,因此在初始化时,“ isPrivate”方法可以完全访问相应实例的属性。

I’ll stop here but feel free to play around with the code. For example, you can try defining a few additional user instances of the Instagram_User class. From there you can practice pulling instance attributes and using the class method ‘isPrivate’. Once you feel comfortable I encourage you to define additional class methods. An interesting method could be one that displays user metrics such as the number of followers, number of people a user follows, and number of posts.

我将在这里停止,但您可以随意使用该代码。 例如,您可以尝试定义Instagram_User类的一些其他用户实例。 从那里,您可以练习提取实例属性并使用类方法“ isPrivate”。 一旦您感到舒适,我鼓励您定义其他的类方法。 一种有趣的方法可能是显示用户指标的方法,例如关注者数量,用户关注的人数以及帖子数量。

结论 (CONCLUSIONS)

To summarize, in this post we discussed the basics of defining classes in python. We showed how to define instances of classes, initialize instances, access instance attributes, and manipulate attributes with methods. The code from this post is available on GitHub. Thank you for reading!

总而言之,在本文中,我们讨论了在python中定义类的基础。 我们展示了如何定义类的实例,初始化实例,访问实例属性以及使用方法操纵属性。 这篇文章中的代码可在GitHub找到。 感谢您的阅读!

翻译自: https://towardsdatascience.com/getting-started-with-python-classes-27bf358b2451

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值