Python 中的点表示法

今天我们来讨论Python中的点表示法。如果您对 Python 编码有一点经验,或者如果您一直关注我们的AskPython 博客,您应该已经遇到过“面向对象编程”这个术语。

它是基于现实世界对象概念的编程范例。每个对象都有某些属性来描述其状态和使它们执行特定任务(相当于执行函数)的方法。Python 就是这样一种语言。

在Python中,几乎每个实体都作为对象进行交易。了解这一点对于理解点 (.) 表示法的意义至关重要。

什么是点符号?

简单来说,点(.)表示法是一种访问不同对象类实例的每个方法的属性和方法的方式。

它前面通常是对象实例,而点符号的右端包含属性和方法。

让我们创建一个具有多个方法的类,然后使用 (.) 表示法来访问这些方法。

创建您的类和对象

class Person():
    def __init__(self, name, age):
        self.name = name
        self.age = age
 
    def sayHello(self):
        print( "Hello, World" )
 
    def sayName(self):
        print( f"My name is {self.name}")
 
"""
First, we create a Person Class that takes two parameters: name, and age. This is an object.
The object currently contains two methods: sayHello() and sayName().
Now, we'll see how we can access those attributes and methods using dot notation from an instance of the class.
"""

现在我们的类已经准备好了,我们需要创建一个实例对象。

#We create an instance of our Person Class to create an object.
randomPerson = Person( "Marshall Mathers", 49)
 
#Checking attributes through dot notation
print( "Name of the person: " + randomPerson.name)
print( "Age of the person: " + str(randomPerson.age) + "years" )
 
#Accessing the attributes through dot notation
randomPerson.sayHello()
randomPerson.sayName()

在最后两行中,我们使用格式为 <对象名称>.<方法名称> 的类对象来访问类中的方法

输出:

Name of the person: Marshall Mathers
Age of the person: 49 years
 
Hello, World
My name is Marshall Mathers

希望上面的示例能够消除您对在 Python 中使用点表示法的疑虑。

我们还可以在哪里使用点表示法?

任何使用过 Python 的开发人员都遇到过 (.) 符号。以下是您过去一定遇到过的一些示例。

1. 列表索引

#A simple list called array with 3 elements
words = ['godzilla', 'darkness', 'leaving heaven']
 
#Getting the index of the list
words.index()

2. 分割字符串

#A random string
pun = "The movie Speed didn't have a director...Because if Speed had direction, it would have been called Velocity."
 
#We use the split method to separate the string into two sections on either side of "..."
print(pun.split("..."))

这些是点表示法的一些日常示例。

结论

点符号不仅仅是访问内部方法的一种方式。这是一种复杂的技术,可以在确保功能完整的同时保持代码简洁和最少。