Python Note 3
Classes
Use Pacal naming convertion,not like variables/function use lower cases and underscore connection.
Basic usage:
class Point : def draw (self ): print ("draw" ) def print (self ): print ("this is point" ) point1 = Point() point1.x = 5 point1.draw() print (point1.x)
Constructor
class Point : def __init__ (self, x, y ): self.x = x self.y = y def draw (self ): print ("draw" ) def print (self ): print ("this is point" ) point1 = Point(10 , 5 ) point1.draw() print (point1.x)class Person : def __init__ (self, name ): self.name = name def talk (self ): print (f"{self.name} is talking.." ) while True : person_name = str (input ("Please enter person: " )) if person_name == "Quit" : break elif person_name != "" : new_person = Person(person_name) new_person.talk() else : print ("You enter a empty!" )
inheritance
use bracket to inherit parent class
class Mammal : def walk (self ): print ("walk" ) class Dog (Mammal ): def bark (self ): print ("bark" ) class Cat (Mammal ): pass dog1 = Dog() dog1.walk() dog1.bark()
module
each file refer a module
import converters from converters import kg_to_lbsimport convertorsfrom convertors import weight_to_lbsprint (weight_to_lbs())numbers = [5 ,1 ,8 ,2 ] maximum = convertors.find_max(numbers) print (max (numbers))
package
a set of modules: directory with “init .py” file
from ecommerce.shopping import testfrom ecommerce import shoppingtest() shopping.test()
use python build-in module
search python module index
PEP: python enhancement proposal
import randommembers = ["Jack" , "Rose" , "Bob" , "Avery" , "Mosh" ] m = random.choice(members) print (m)import randomclass Dice : def roll (self ): r1 = random.randint(0 , 5 ) r2 = random.randint(0 , 5 ) return r1,r2 mydice = Dice() print (mydice.roll())
from pathlib import Pathpath = Path("pydemo2/ecommerce" ) for p in path.glob("*.py" ): print (p)
使用type直接拿到类句柄
result = type (self)(self.a)