程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

The second notes of 2022 Python winter vacation advanced training

編輯:Python

Dynamically add properties and methods to instances

Example :

from types import MethodType # For dynamically adding methods , introduce MethodType
class cat(object):
pass # Define an empty class
cat1 = cat()
cat1.name = "Tom" # Add properties dynamically
print(cat1.name)
def run(self): # Define a method first
print(self.name+" Running ")
cat.run = MethodType(run,cat1) # Dynamic add method
cat1.run() # Calling method

Restrict dynamically adding attributes __slots__

class cat(object): __slots__=("name","age") # Restrict instance properties , Only attributes in parentheses can be added

operator overloading

 

Example :__add__

class Person(object):
def __init__(self,num):
self.num = num
# Operator overloading
def __add__(self, other):
return Person(self.num + other.num)
def __str__(self):
return "num = "+str(self.num)
per1 = Person(1)
per2 = Person(2)
print(per1+per2)

__lt__ :

# operator.lt(a, b)
import operator
# print(operator.lt(3, 2)) # The front number is less than the back number by Ture
# print(operator.lt(1, 2)) # The front number is greater than the back number by False
class Grade(object):
def __init__(self,num):
self.num = num
#lt Operator overloading
def __lt__(self, other):
if self.num > other.num: # Colons must be different. Forget
return 1
if self.num == other.num:
return 0
if self.num < other.num:
return 2
# def __str__(self):
# return "num = "+str(self.num)
# print(pow(2,2))
gra1 = Grade(2)
gra2 = Grade(3)
print(operator.lt(gra2, gra1))
# print(pow(gra1,2))

__pow__ # square

class Grade(object):
def __init__(self,num):
self.num = num
#lt Operator overloading square
def __pow__(self, power, modulo=None):
return Grade(pow(self.num,power))
def __str__(self):
return "num = "+str(self.num)
# print(pow(2,2))
gra1 = Grade(2) # Define an object
print(pow(gra1,2)) # Overloading of validation operators
pow Explain :
https://blog.csdn.net/weixin_39712705/article/details/112315901

operator --- Standard operators replace functions :


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved