Python入門系列(七)開發常說的「累」與「對象」
- 2022 年 9 月 1 日
- 筆記
類與對象
Python是一種面向對象的程式語言。
要創建類,請使用關鍵字class
class MyClass:
x = 5
創建一個名為p1的對象,並列印x的值
p1 = MyClass()
print(p1.x)
所有類都有一個名為__init_()的函數,該函數總是在初始化類時執行。
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
對象也可以包含方法。對象中的方法是屬於對象的函數。
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
self參數是對類的當前實例的引用,用於訪問屬於該類的變數。
它不必命名為self,您可以隨意調用它,但它必須是類中任何函數的第一個參數:
# Use the words mysillyobject and abc instead of self
class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("John", 36)
p1.myfunc()
您可以修改以下對象的屬性
p1.age = 40
可以使用del關鍵字刪除對象上的屬性
del p1.age
可以使用del關鍵字刪除對象
del p1
Python繼承
創建父類
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
#Use the Person class to create an object, and then execute the printname method:
x = Person("John", "Doe")
x.printname()
創建子類
class Student(Person):
pass
使用Student類創建對象,然後執行printname方法
x = Student("Mike", "Olsen")
x.printname()
添加__init_()函數時,子類將不再繼承父類的_ init_()函數。
class Student(Person):
def __init__(self, fname, lname):
#add properties etc.
要保留父函數的__init_()函數的繼承,請添加對父函數的調用
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)
Python還有一個super()函數,它將使子類繼承其父類的所有方法和屬性
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
通過使用super()函數,您不必使用父元素的名稱,它將自動從其父元素繼承方法和屬性。
添加屬性
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
x = Student("Mike", "Olsen", 2019)
print(x.graduationyear)
添加方法
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
def welcome(self):
print("Welcome", self.firstname, self.lastname, "to the class of", self.graduationyear)
Python迭代器
列表、元組、字典和集合都是可迭代對象。它們是可迭代的容器,您可以從中獲取迭代器。
mytuple = ("apple", "banana", "cherry")
myit = iter(mytuple)
print(next(myit))
print(next(myit))
print(next(myit))
創建迭代器
__iter__()方法的作用類似,您可以執行操作(初始化等),但必須始終返回迭代器對象本身。
__next_()方法還允許您執行操作,並且必須返回序列中的下一項。
class MyNumbers:
def __iter__(self):
self.a = 1
return self
def __next__(self):
x = self.a
self.a += 1
return x
myclass = MyNumbers()
myiter = iter(myclass)
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
為了防止迭代永遠持續下去,我們可以使用StopIteration語句。
class MyNumbers:
def __iter__(self):
self.a = 1
return self
def __next__(self):
if self.a <= 20:
x = self.a
self.a += 1
return x
else:
raise StopIteration
myclass = MyNumbers()
myiter = iter(myclass)
for x in myiter:
print(x)
作用域
如以上示例所述,變數x在函數外部不可用,但在函數內部的任何函數中都可用
def myfunc():
x = 300
def myinnerfunc():
print(x)
myinnerfunc()
myfunc()
如果需要創建全局變數,但仍停留在局部範圍內,則可以使用global關鍵字。
Python模組
要創建模組,只需將所需程式碼保存在文件擴展名為.py的文件中
# Save this code in a file named mymodule.py
def greeting(name):
print("Hello, " + name)
現在,我們可以使用剛才創建的模組,方法是使用import語句
import mymodule
mymodule.greeting("Jonathan")
模組中的變數
# Save this code in the file mymodule.py
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
import mymodule
a = mymodule.person1["age"]
print(a)
導入模組時,可以使用as關鍵字創建別名
import mymodule as mx
a = mx.person1["age"]
print(a)
有一個dir()函數來列出模組中的所有函數名(或變數名)
import platform
x = dir(platform)
print(x)
通過使用from關鍵字,您可以選擇僅從模組導入零件。
def greeting(name):
print("Hello, " + name)
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
from mymodule import person1
print (person1["age"])
您的關注,是我的無限動力!
公眾號 @生活處處有BUG