我爱编程

2018-04-14 开胃学习Python系列 - Object

2018-04-14  本文已影响0人  Kaiweio

Python也是oop,虽然函数在Python生态系统中扮演重要角色。Python确实具有类别(classes) 可以有附加的方法(method),并被具现化为物件(object)。

实际上,虽然将在Python中使用很多object, 但是当使用interactive 环境时,我们不太可能会创建新的class,因为有点太详细冗长。





首先,我们是可以定义一个class,使用class关键字,并以冒号结尾。我几乎没有这么做过,但是我写这一篇的原因就是因为我第一次见到了self这个写法。因为大多时候做一些简单的数据出来,我没有用python创建过class,所以之前也没有写过self,和init。但这两个用法都基本是只要熟悉了就好了。

class Person:
    department = 'School of Information' 
#a class variable

    def set_name(self, new_name): #a method
        self.name = new_name
    def set_location(self, new_location):
        self.location = new_location​

class

方法(method)

例如,在此定义中,写了两种方法(method)。
设置名称和设置的位置。这两个变化实例绑定的变数,分别称为名称和位置。





调用它的函数功能,列印出class属性,使用 点标记法(dot-notation)

person = Person()
person.set_name('Christopher Brooks')
person.set_location('Ann Arbor, MI, USA')
print('{} live in {} and works in the department {}'.format\
(person.name, person.location, person.department))
>>> Christopher Brooks live in Ann Arbor, MI, USA and works in the department School of Information





But functional programming causes one to think more heavily while chaining operations together. And this really is a sort of underlying theme in much of data science and date cleaning in particular. So, functional programming methods are often used in Python, and it's not uncommon to see a parameter for a function, be a function itself. The map built-in function is one example of a functional programming feature of Python, that I think ties together a number of aspects of the language. The map function signature looks like this. The first parameters of function that you want executed, and the second parameter, and every following parameter, is something which can be iterated upon.

map内置功能是Python的函数程式语言功能的一个例子

store1 = [10.00, 11.00, 12.34, 2.34]
store2 = [9.00, 11.10, 12.34, 2.01]
cheapest = map(min, store1, store2)
cheapest
>>><map at 0x7f18301726d8>

for item in cheapest:
    print(item)
#output
>>>
9.0
11.0
12.34
2.01
People = ['Dr. Christopher Brooks', 'Dr. Kevyn Collins-Thompson', 
'Dr. VG Vinod Vydiswaran', 'Dr. Daniel Romero']

def split_title_and_name(person):
    return person.split(' ')[0] + person.split(' ')[2]

list(map(split_title_and_name, people))
上一篇 下一篇

猜你喜欢

热点阅读