Python类

作者: 爆炸的白菜君 | 来源:发表于2019-01-07 11:55 被阅读3次

python中的类其实是一个对象。这就是为什么在类中定义的属性,在所有对象中通用。也就是说类A中有number这个属性,默认值是0。实例1修改number为5后。实例2,再获取number这个属性,就是5。这和Swift以及OC不一样。

创建一个类有两种方法

  • 使用关键字 class
  • 使用type函数
class TestClass(object):
  pass
def testAction(self):
    print "testAction---%s" %self.name

TestClass2 = type('TestClass2',(TestClass1,),{'testAction':testAction, 'name':'yhl'})
#注意这里的 TestClass 必须继承object类

print TestClass2

类方法,关键字 @classmethod

@classmethod
def test3Action(cls):
    print 'test3Action %s' %cls

静态方法,关键字@staticmethod

@staticmethod
def test2Action():
    print "test2Action"

元类

元类是创建类的类
类是创建实例的对象

type就是一个元类,所以他可以创建其他的类

yhl = 100

print  yhl.__class__
print yhl.__class__.__class__

#打印结果
<type 'int'>
<type 'type'>

metaclass属性

你首先写下 class Foo( object),但是类Foo还没有在内存中创建。 Python
会在类的定义中寻找metaclass属性,如果到了, Python就会用它来
创建类Foo,如果没有找到,就会用内建的type来创建这个类

现在的问题就是,你可以在 metaclass中放置些什么代码呢?
答案就是:可以创建一个类的东西。那么什么可以用来创建一个类呢?type,或者任何使用到ype或者子类化type的东东都可以。

相关文章

网友评论

      本文标题:Python类

      本文链接:https://www.haomeiwen.com/subject/suyyrqtx.html