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

Common advanced functions of Python classes

編輯:Python

__init__

# coding:utf-8
if __name__ == '__main__':
''' Definition :def __init__(self, Parameters 1, Parameters 2......): ...... Use : Trigger when the class is instantiated Class name ( Parameters 1, Parameters 2.......) '''
class A(object):
def __init__(self, name, sex):
print(f'name is {
name}, sex is {
sex}')
a = A('xie', 'man') # name is xie, sex is man

__getattr__

# coding:utf-8
if __name__ == '__main__':
''' Definition : def __getattr(self, Property name ) Use : Triggered when an attribute of a class that does not exist or does not have permission is accessed object. Property name '''
class B(object):
__name = 'rui'
name = 'xie'
def __getattr__(self, name):
return f'name is {
name}'
b = B()
print(b.name) # xie
print(b.__name) # name is __name
print(b.sex) # name is sex
print(b._B__name) # rui

__setattr__

# coding:utf-8
if __name__ == '__main__':
''' Definition : def __setattr__(self, Property name , Property value ) Use : Triggered when a property value is set for a class object. Property name = Property value '''
class C(object):
name = ''
__name = ''
__sex = ''
def __setattr__(self, key, value):
print(f'I want set key:{
key},value:{
value}')
c = C()
c.name = 'xie' # I want set key:name,value:xie
c.age = '6666' # I want set key:age,value:6666
c.__sex = 'man' # I want set key:__sex,value:man

__call__

# coding:utf-8
if __name__ == '__main__':
''' Definition : def __call__(self, Parameters 1, Parameters 2......) Use : Treat class instances as function calls , adopt object( Parameters 1, Parameters 2......) Trigger '''
class D(object):
def __call__(self, *args, **kwargs):
print(f'args is {
args},kwargs is {
kwargs}')
d = D()
d(*(1, 2, 3), **{
'name': 'xie'}) # args is (1, 2, 3),kwargs is {'name': 'xie'}

__str__

# coding:utf-8
if __name__ == '__main__':
''' Definition : def __str__(self) Use : Triggered when an object is printed print(object) '''
class F(object):
def __str__(self):
return ' Commonly used to describe classes '
f = F()
print(f) # Commonly used to describe classes 

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