构造器方法与解构器方法:
# 一般可以理解类中的函数就是方法,而方法分为:
# 实例方法,只有实例化后才能调用的,其第一个参数一般为 self,代表实例本身;
# 类方法,其第一个参数为 cls,代表类本身;
# 静态方法,就是个普通函数,没有要求参数。
类属性和实例属性:
class Test(object):
name = 'liu' # 类公有属性
@classmethod
def get_v(cls):
return cls.name
@classmethod
def set_v(cls, value):
cls.name = value
a = Test()
print Test.name, a.name # 结果:liu liu
# 通过类进行修改
Test.name = 'tian'
print Test.name, a.name # 结果:tian tian
# 通过实例进行修改
a.name = 'love'
print Test.name, a.name # 结果:tian love
# 通过方法进行修改:a调用set_v和get_v的时候,cls绑定a.__class__。
a.set_v("like")
print Test.name, a.name # 结果:like love
# 类内的变量和方法能被此类所创建的所有实例所共同拥有。
# 1.类变量:类与对象都能调用。
# 2.类变量类能调用(类.变量和类.get()获取)与修改(类.变量=6和类.set()修改)。
# 调用:A.name A.get_v()
# 修改:A.name =6 A.set_v()
# 3.类变量对象能调用(对象.变量和对象.get()获取),能修改(对象.set()修改)。
# 调用:a.name a.get_v()
# 修改:a.set_v()
# 附加:不能使用 a.name="love" 来修改类变量。这样就变成给对象添加新的属性了。
类的三种方法:
https://www.cnblogs.com/kaituorensheng/p/5693677.html
https://blog.youkuaiyun.com/abc_12366/article/details/80437478
特殊方法与属性:
# 1.函数 dir() 就能查看对象的属性:
# 2.函数 vars()传给函数一个对象,将对象内的属性和值用字典的方式显示出来。
# -*- coding:utf-8 -*-
class Test(object):
love = 'hua' # 类属性
__mm = 26 # 类私有属性
def __init__(self, name, age):
self.name = name
self.age = age
def sayhello(self):
print "hello python!"
t = Test("liu", 26)
t.sex = "男"
print dir(Test) # 结果:['_Test__mm', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'love', 'sayhello']
print dir(t) # 结果:['_Test__mm', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'love', 'name', 'sayhello', 'sex']
print vars(Test) # 结果:{'__module__': '__main__', 'love': 'hua', '_Test__mm': 26, 'sayhello': <function sayhello at 0x00000000108524A8>, '__dict__': <attribute '__dict__' of 'Test' objects>, '__weakref__': <attribute '__weakref__' of 'Test' objects>, '__doc__': None, '__init__': <function __init__ at 0x0000000010852438>}
print vars(t) # 结果:{'age': 26, 'name': 'liu', 'sex': '\xe7\x94\xb7'}
本文深入探讨Python中类与对象的概念,包括构造器与解构器方法、实例方法与类方法的区别,以及类属性和实例属性的使用。通过具体代码示例,解析类变量与实例变量的调用与修改方式,帮助读者理解类与对象之间的关系。

被折叠的 条评论
为什么被折叠?



