zoukankan      html  css  js  c++  java
  • Python入门 面向对象

    简单Try

    class Student(object):
    	def __init__(self, name, score):
    		self.name=name
    		self.score = score
    
    	def print_score(self):
    		print("%s %s" %(self.name, self.score))
    
    
    dd = Student('draymonder', 21)
    bb = Student('bing', 21)
    
    dd.print_score()
    

    访问限制

    如果要让内部属性不被外部访问,可以把属性的名称前加上两个下划线__,在Python中,实例的变量名如果以__开头,就变成了一个私有变量(private),只有内部可以访问,外部不能访问

    实际上是可以访问的,只是_规范程序员以私有变量来使用
    具体访问如下

    class Student(object):
    	def __init__(self, name, score):
    		self.__name=name
    		self.__score = score
    
    	def print_score(self):
    		print("%s %s" %(self.__name, self.__score))
    
    
    dd = Student('draymonder', 21)
    print(dd._Student__name)
    

    print(dd._Student__name)

    @property

    内置的@property装饰器就是负责把一个方法变成属性调用的

    class Student(object):
    
    	@property
    	def birth(self):
    		return self._birth
    	
    	@birth.setter
    	def birth(self, vale):
    		self._birth = value
    
    	@property
    	def age(self):
    		return 2019 - self._birth
    
    s = Student()
    s._birth = 1998
    print(s.age)
    

    getattr

    class Chain(object):
    
        def __init__(self, path=''):
            self._path = path
    
        def __getattr__(self, path):
            return Chain('%s/%s' % (self._path, path))
    
        def __str__(self):
            return self._path
    
        __repr__ = __str__
    
    print(Chain().status.user.timeline.list)
    

    使用元类

    创建类

    def fn(self, name="world"):
    	print("hello %s" %name)
    
    Hello = type("hello", (object,), dict(hello=fn)) #创建hello class
    

    list添加add方法

    class ListMetaclass(type):
    	def __new__(cls, name, bases, attrs):
    		attrs['add'] = lambda self,value: self.append(value)
    		return type.__new__(cls, name, bases, attrs)
    
    class MyList(list, metaclass = ListMetaclass):
    	pass
    
    L = MyList()
    L.add(1)
    L.add(2)
    L.add(3)
    print(L)
    

    简易ORM模型

    class ModelMetaclass(type):
        def __new__(cls, name, bases, attrs):
            if name=='Model':
                return type.__new__(cls, name, bases, attrs)
            print('Found model: %s' % name)
            mappings = dict()
            for k, v in attrs.items():
                if isinstance(v, Field):
                    print('Found mapping: %s ==> %s' % (k, v))
                    mappings[k] = v
            for k in mappings.keys():
                attrs.pop(k)
            attrs['__mappings__'] = mappings # 保存属性和列的映射关系
            attrs['__table__'] = name # 假设表名和类名一致
            return type.__new__(cls, name, bases, attrs)
    
    
    class Model(dict, metaclass=ModelMetaclass):
        def __init__(self, **kw):
            super(Model, self).__init__(**kw)
    
        def __getattr__(self, key):
            try:
                return self[key]
            except KeyError:
                raise AttributeError(r"'Model' object has no attribute '%s'" % key)
    
        def __setattr__(self, key, value):
            self[key] = value
    
        def save(self):
            fields = []
            params = []
            args = []
            for k, v in self.__mappings__.items():
                fields.append(v.name)
                params.append('?')
                args.append(getattr(self, k, None))
            sql = 'insert into %s (%s) values (%s)' % (self.__table__, ','.join(fields), ','.join(params))
            print('SQL: %s' % sql)
            print('ARGS: %s' % str(args))
    
    
    
    
    # Field(name, column_type)
    class Field(object):
    	def __init__(self, name, column_type):
    		self.name = name
    		self.column_type = column_type
    
    	def __str__(self):
    		return "<%s:%s>" %(self.__class__.__name__, self.name)
    
    class StringField(Field):
    	def __init__(self, name):
       		super(StringField, self).__init__(name, 'varchar(100)')
    
    class IntegerField(Field):
        def __init__(self, name):
            super(IntegerField, self).__init__(name, 'bigint')
    
    class User(Model):
    	id = IntegerField("id")
    	name = StringField("username")
    	email = StringField("email")
    	password = StringField("password")
    
    
    
    
    u = User(id=1,name="draymonder",email="93958042@qq.com",password="IloveU")
    u.save()
    

    参考文章

    python面向对象编程

  • 相关阅读:
    HBase with MapReduce (MultiTable Read)
    HBase with MapReduce (SummaryToFile)
    HBase with MapReduce (Summary)
    HBase with MapReduce (Read and Write)
    HBase with MapReduce (Only Read)
    Hbase中的BloomFilter(布隆过滤器)
    HBase的快照技术
    How To Use Hbase Bulk Loading
    Cloudera-Manager修改集群的IP
    Java中的HashSet和TreeSet
  • 原文地址:https://www.cnblogs.com/Draymonder/p/10671417.html
Copyright © 2011-2022 走看看