知乎 - 知乎Python基礎介紹 | Class類6 人贊了文章自從改用Python做數據挖掘以來,我就很少用面向對象的內容了,那啥是面..." />

Python基礎介紹 | Class類

tml lang="zh" data-theme="light">知乎 - 知乎

Python基礎介紹 | Class類

6 人贊了文章

自從改用Python做數據挖掘以來,我就很少用面向對象的內容了,那啥是面向對象呢?

可以這麼理解,如果我們能把代碼組合成一個一個可以重複使用的類別,那麼這能使程序的可復用性更高,以後只要用這個類別的東西就好,不用再重複實現這樣的內容了。

Class 類

以下是類的構建,跟函數一樣,前面需要用class聲明

class MyFirstClass:
def __init__(self, name):
self.name = name

def greet(self):
print(Hello {}!.format(self.name))

現在來實例化一個類

my_instance = MyFirstClass(John Doe)
print(my_instance: {}.format(my_instance))
print(type: {}.format(type(my_instance)))
print(my_instance.name: {}.format(my_instance.name))

做完以上的兩個,你就實現了類的構建,並成功實例化了一個類。

Methods 函數

類中的函數稱為方法,使用方式和一般的函數一樣

alice = MyFirstClass(name=Alice)
alice.greet()

以上的輸出,當然是Hello Alice!

__init__() 此方法曾困擾了我好久

__init__()是一種特殊的方法,用於初始化類的實例,在創建類的時候調用它

class Example:
def __init__(self):
print(Now we are inside __init__)

print(creating instance of Example)
example = Example()
print(instance created)

__init__()通常用於初始化類的實例變數。這些可以作為參數列出self。為了能夠在實例的生命周期中稍後訪問這些實例變數,你必須將它們保存到self。self是類的方法的第一個參數,它是ni對實例變數和其他方法的訪問方式。

class Example:
def __init__(self, var1, var2):
self.first_var = var1
self.second_var = var2

def print_variables(self):
print({} {}.format(self.first_var, self.second_var))

e = Example(abc, 123)
e.print_variables()

做數據分析的時候,或許可以將很多語句拼湊起來完成數據的分析,但當涉及到更長遠的考量,如果無法提高代碼的復用率,那你就得每次都重新寫一遍代碼 for a life long time。

__str__()

__str__()是一個特殊的方法,當類的實例轉換為字元串時調用(例如,當你想要列印實例時)。換句話說,通過__str__為你的類定義方法,你可以決定類的實例的可列印版本。該方法應返回一個字元串。

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def __str__(self):
return Person: {}.format(self.name)

jack = Person(Jack, 82)
print(This is the string presentation of jack: {}.format(jack))

類的變數與實例變數

類變數在該類的所有實例之間共享,而實例變數可以在該類的不同實例之間保存不同的值。

class Example:
# These are class variables
name = Example class
description = Just an example of a simple class

def __init__(self, var1):
# This is an instance variable
self.instance_variable = var1

def show_info(self):
info = instance_variable: {}, name: {}, description: {}.format(
self.instance_variable, Example.name, Example.description)
print(info)

inst1 = Example(foo)
inst2 = Example(bar)

# name and description have identical values between instances
assert inst1.name == inst2.name == Example.name
assert inst1.description == inst2.description == Example.description

# If you change the value of a class variable, its changed across all instances
Example.name = Modified name
inst1.show_info()
inst2.show_info()

Public 與 Private變數

在python中,現在嚴格分離私有/公共方法或實例變數。如果一個變數是私有變數的話,慣例是使用下劃線開始方法或實例變數的名稱。私有意味著不應該從類外訪問它。

例如,讓我們考慮一下我們有一個Person具有age實例變數的類。我們希望age在創建實例後不直接訪問(例如更改)。在Python中,這將是:

class Person:
def __init__(self, age):
self._age = age

example_person = Person(age=15)
# You cant do this:
# print(example_person.age)
# Nor this:
# example_person.age = 16

如果你想要age可讀但不可寫,那可以使用property:

class Person:
def __init__(self, age):
self._age = age

@property
def age(self):
return self._age

example_person = Person(age=15)
# Now you can do this:
print(example_person.age)
# But not this:
#example_person.age = 16

這樣,你就可以對類的實例變數進行受控訪問:

class Person:
def __init__(self, age):
self._age = age

@property
def age(self):
return self._age

def celebrate_birthday(self):
self._age += 1
print(Happy bday for {} years old!.format(self._age))

example_person = Person(age=15)
example_person.celebrate_birthday()

類的繼承

如果你不知道類的繼承是什麼,你就類比生物中的繼承關係,而面向對象編程的思想,你也該去了解一下,非常簡單。

class Animal:
def greet(self):
print(Hello, I am an animal)

@property
def favorite_food(self):
return beef

class Dog(Animal):
def greet(self):
print(wof wof)

class Cat(Animal):
@property
def favorite_food(self):
return fish

現在實例一下以上的類

dog = Dog()
dog.greet()
print("Dogs favorite food is {}".format(dog.favorite_food))

cat = Cat()
cat.greet()
print("Cats favorite food is {}".format(cat.favorite_food))

推薦閱讀:

TAG:Python入門 | Python | Python開發 |