Python一切皆对象(object),每个对象都可能有多个属性(attribute)。Python的属性有一套统一的管理方案。
对象的属性可能来自于其类定义,叫做类属性(class attribute)。
类属性可能来自类定义自身,也可能根据类定义继承来的。
一个对象的属性还可能是该对象实例定义的,叫做对象属性(object attribute)。
对象的属性储存在对象的__dict__属性中。
__dict__为一个词典,键为属性名,对应的值为属性本身。我们看下面的类和对象。
对应Java的反射中,来获取对象的属性,如:
public class UserBean { private Integer id; private int age; private String name; private String address; } //类实例化 UserBean bean = new UserBean(); bean.setId(100); bean.setAddress("武汉"); //得到类对象 Class userCla = (Class) bean.getClass(); //得到类中的所有属性集合 Field[] fs = userCla.getDeclaredFields(); ......
class bird(object): feather = True class chicken(bird): fly = False def __init__(self, age): self.age = age summer = chicken(2) print(bird.__dict__) print(chicken.__dict__) print(summer.__dict__)
输出:
{'__dict__': a06c3452ae36a3b1829ca9e9ce47cf5b, '__module__': '__main__', '__weakref__': 55b8b94dfd5b7b5eeff561a93e026066, 'feather': True, '__doc__': None}
{'fly': False, '__module__': '__main__', '__doc__': None, '__init__': c51d1476b57e7fe91e8dedc84c3b2a0c}
{'age': 2}
第一行为bird类的属性,比如feather。
第二行为chicken类的属性,比如fly和__init__方法。
第三行为summer对象的属性,也就是age。
有一些属性,比如__doc__,并不是由我们定义的,而是由Python自动生成。此外,bird类也有父类,是object类(正如我们的bird定义,class bird(object))。这个object类是Python中所有类的父类。
也就是子类的属性,会覆盖父类的属性。
可以通过下面2中方法修改类的属性:
summer.__dict__['age'] = 3 print(summer.__dict__['age']) summer.age = 5 print(summer.age)
Python中的property
同一个对象的不同属性之间可能存在依赖关系。当某个属性被修改时,我们希望依赖于该属性的其他属性也同时变化。这时,我们不能通过__dict__的方式来静态的储存属性。Python提供了多种即时生成属性的方法。其中一种称为特性(property)。
class bird(object): feather = True #extends bird class class chicken(bird): fly = False def __init__(self, age): self.age = age def getAdult(self): if self.age > 1.0: return True else: return False adult = property(getAdult) # property is built-in summer = chicken(2) print(summer.adult) summer.age = 0.5 print(summer.adult)
这里的功能类似于触发器。在每次获取adult属性的时候,会触发getAdult的值。
特性使用内置函数property()来创建。property()最多可以加载四个参数。前三个参数为函数,分别用于处理查询特性、修改特性、删除特性。最后一个参数为特性的文档,可以为一个字符串,起说明作用。
class num(object): def __init__(self, value): self.value = value print '<--init' def getNeg(self): print '<--getNeg' return self.value * -1 def setNeg(self, value): print '<--setNeg' self.value = (-1) * value def delNeg(self): print("value also deleted") del self.value neg = property(getNeg, setNeg, delNeg, "I'm negative") x = num(1.1) print(x.neg) x.neg = -22 print(x.value) print(num.neg.__doc__) del x.neg
整个过程之中,都没有调用对应的几个函数。
也就是说,neg这个属性的创建,设置,删除都通过property()注册起来了。
Python特殊方法__getattr__ (这个常用)
我们可以用__getattr__(self, name)来查询即时生成的属性。
在pyhton中,对象属性都是动态的,随时可以根据需要添加或者删除属性。
那么getattr的作用就是,在产生这些属性的时候,进行一层判断处理操作。
比如:
class bird(object): feather = True class chicken(bird): fly = False def __init__(self, age): self.age = age def __getattr__(self, name): if name == 'adult': if self.age > 1.0: return True else: return False else: raise AttributeError(name) summer = chicken(2) print(summer.adult) summer.age = 0.5 print(summer.adult) print(summer.male)
每个特性需要有自己的处理函数,而__getattr__可以将所有的即时生成属性放在同一个函数中处理。__getattr__可以根据函数名区别处理不同的属性。比如上面我们查询属性名male的时候,raise AttributeError。
(Python中还有一个__getattribute__特殊方法,用于查询任意属性。
__getattr__只能用来查询不在__dict__系统中的属性)
__setattr__(self, name, value)和__delattr__(self, name)可用于修改和删除属性。
它们的应用面更广,可用于任意属性。

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

useanArray.ArarayoveralistinpythonwhendeAlingwithHomeSdata,performance-Caliticalcode,orinterFacingWithCcccode.1)同质性data:arrayssavememorywithtypedelements.2)绩效code-performance-clitionalcode-clitadialcode-critical-clitical-clitical-clitical-clitaine code:araysofferferbetterperperperformenterperformanceformanceformancefornalumericalicalialical.3)

不,notalllistoperationsareSupportedByArrays,andviceversa.1)arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,wheremactssperformance.2)listssdonotguaranteeconeeconeconstanttanttanttanttanttanttanttanttimecomplecomecomecomplecomecomecomecomecomecomplecomectaccesslikearrikearraysodo。

toAccesselementsInapythonlist,useIndIndexing,负索引,切片,口头化。1)indexingStartSat0.2)否定indexingAccessesessessessesfomtheend.3)slicingextractsportions.4)iterationerationUsistorationUsisturessoreTionsforloopsoreNumeratorseforeporloopsorenumerate.alwaysCheckListListListListlentePtotoVoidToavoIndexIndexIndexIndexIndexIndExerror。

Arraysinpython,尤其是Vianumpy,ArecrucialInsCientificComputingfortheireftheireffertheireffertheirefferthe.1)Heasuedfornumerericalicerationalation,dataAnalysis和Machinelearning.2)Numpy'Simpy'Simpy'simplementIncressionSressirestrionsfasteroperoperoperationspasterationspasterationspasterationspasterationspasterationsthanpythonlists.3)inthanypythonlists.3)andAreseNableAblequick

你可以通过使用pyenv、venv和Anaconda来管理不同的Python版本。1)使用pyenv管理多个Python版本:安装pyenv,设置全局和本地版本。2)使用venv创建虚拟环境以隔离项目依赖。3)使用Anaconda管理数据科学项目中的Python版本。4)保留系统Python用于系统级任务。通过这些工具和策略,你可以有效地管理不同版本的Python,确保项目顺利运行。

numpyarrayshaveseveraladagesoverandastardandpythonarrays:1)基于基于duetoc的iMplation,2)2)他们的aremoremoremorymorymoremorymoremorymoremorymoremoremory,尤其是WithlargedAtasets和3)效率化,效率化,矢量化函数函数函数函数构成和稳定性构成和稳定性的操作,制造


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

EditPlus 中文破解版
体积小,语法高亮,不支持代码提示功能

Atom编辑器mac版下载
最流行的的开源编辑器

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

Dreamweaver CS6
视觉化网页开发工具

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。