Python 类相关总结

 关于Python类相关的一些基础总结,很基础的东西!

1. 测试META与hasattr():

class ClassTest(object):

    username = 'fxx'

    def test_has_attr(self):
        if hasattr(self, 'username'):
            print('我有username属性!')
        else:
            print('我没有该属性!')

    class Mata:
        model = 'fxx'

    class Meta:
        model = 'gxx'

    def test_meta(self):
        print(self.Meta.model)
        print(self.Mata.model)


test = ClassTest()
test2 = ClassTest

print(type(test))    # <class '__main__.ClassTest'>
print(id(test))    # 4518266920

print(type(test2))    # <class 'type'>
print(id(test2))    # 140500879331320

print(id(ClassTest))    # 140500879331320

test.test_meta()    # gxx    fxx
test.test_has_attr()    # 我有username属性!

 

2. 属性方法、类方法、静态方法

class TestMethod(object):
    """测试实例方法、类方法和静态方法"""

    def attr_method(self):
        print('我是实例方法!')

    @classmethod
    def class_method(cls):
        print('我是类方法!')

    @staticmethod
    def static_method():
        print('我是静态方法!')


print(isinstance(test_method, TestMethod))  # True

test_method = TestMethod()

test_method.attr_method()  # 我是实例方法!
test_method.class_method()  # 我是类方法!
test_method.static_method()  # 我是静态方法!


TestMethod.class_method()  # 我是类方法!
TestMethod.static_method()  # 我是静态方法!
TestMethod.attr_method(test_method)  # 我是实例方法!
TestMethod.attr_method()  # TypeError: attr_method() missing 1 required positional argument: 'self'
  • 实例方法传入的参数为一个实例对象,因此只有对象才可以调用,如果使用类直接调用实例方法,需要显式地将实例作为参数传入。
  • 类方法传入的参数为该方法前面的类,由 isinstance(test_method, TestMethod) = True 可知,实例对象和类其实属于同种类型,因此对象和类都可以调用类方法。
  • 静态方法不需要传入对象或者类,因此类和对象都可以调用。

 

3. 关于多重继承和继承顺序

如果继承的两个类都同时定义了一个方法,继承后,会得到哪一个方法?

其中一个类(GenericAPIView(APIView(View)))定义了一个方法as_view(),另一个类(ViewSetMixin)重写了as_view(),他们先后顺序的关系?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值