python语法_类和语句

python类

类的init函数

#类定义
class people:
    #定义基本属性
    name = ''
    age = 0
    #定义私有属性,私有属性在类外部无法直接进行访问
    __weight = 0
    #定义构造方法
    def __init__(self,n,a,w):
        self.name = n
        self.age = a
        self.__weight = w
    def speak(self):
        print("%s 说: 我 %d 岁。" %(self.name,self.age))
 
# 实例化类
p = people('runoob',10,30)
p.speak()

类继承

#定义父类:Parent
class Parent(object):
    def __init__(self, name):
        self.name = name
        print("create an instance of:", self.__class__.__name__)
        print("name attribute is:", self.name)
#定义子类Child ,继承父类Parent
class Child(Parent):
    pass
#子类实例化时,由于子类没有初始化,此时父类的初始化函数就会默认被调用
#且必须传入父类的参数name
c = Child("init Child")
print(c.name)

super父类初始化

python语句

encoding标头

#coding:utf-8

try-exception

        try:
            cql_node = match_sql + r_sql + where_sql + return_sql
            node = self.graph.run(cql_node).data()
        except Exception:
            print('[ERROR] cant get node from neo4j!')
            traceback.print_exc()
        else:
            return node

三目运算符

a = 10
9 if a>8 else 10

out: 9

match=('teacher'
    if len(node_type)!=0 else 'hi')

赋值时必须有括号;

for语句创建dict

from collections import defaultdict
type_corners = {ltype:defaultdict(set) for ltype in useful_types}

type_corners:
{1: defaultdict(set, {}),
2: defaultdict(set, {}),
3: defaultdict(set, {}),
4: defaultdict(set, {})}

enumerate语句

for i, homo_att in enumerate(self.HomoAttModels):

其他

traceback打印语句

traceback.print_exc()

posted @ 2021-02-25 18:59  zae  阅读(104)  评论(0编辑  收藏  举报