美文网首页
Python的学习

Python的学习

作者: 哥只是个菜鸟 | 来源:发表于2020-07-14 16:45 被阅读0次

基础教程链接

注意点

1.全局变量和局部变量

string='hahhasdshdshdks'#全局变量
def getpass(haha):
    # global string  #加上global表示这里赋值的是全局变量
    string='yyyyyy'
    if haha <5:
        print('dd')
        return haha*2
print('string改变前==',string)
getpass(3)
print('string改变后==', string)

2.新建一个类

class HelloWorld:
    helloCount=0
    __secrectCount=0;#私有变量
    def __init__(self,name,salary):#初始化方法
      self.name = name
      self.salary = salary
      HelloWorld.helloCount += 1
      self.__pricateCount()

    def displayCount(self):
        print('count',HelloWorld.helloCount)
    def __del__(self):
        print('')
    def __pricateCount(self):
        print('私有方法调用')

hello = HelloWorld("dd",34)
hello.displayCount()
print('hello.__doc__',hello.__module__)
print('hello.__name__',hello.__class__.__name__)
print('hello.__dict__',hello.__dict__)

3.运算符重载

class Vector:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __str__(self):
        return 'Vector (%d, %d)' % (self.a, self.b)

    def __add__(self, other):
        return Vector(self.a + other.a, self.b + other.b)


v1 = Vector(2, 10)
v2 = Vector(2,4)
print('ddd',v1+v2)
  • 类的私有属性
    __private_attrs:两个下划线开头,声明该属性为私有,不能在类的外部被使用或直接访问。在类内部的方法中使用时 self.__private_attrs。
  • 类的方法
    在类的内部,使用 def 关键字可以为类定义一个方法,与一般函数定义不同,类方法必须包含参数 self,且为第一个参数
  • 类的私有方法
    __private_method:两个下划线开头,声明该方法为私有方法,不能在类的外部调用。在类的内部调用 self.__private_methods

5.如果想从同目录下的另一个文件访问some_module.py中定义的变量和函数,可以:

from some_module import f, g, PI
result = g(5, PI)

6.使用as关键词,你可以给引入起不同的变量名:

import some_module as sm
from some_module import PI as pi, g as gf

r1 = sm.f(pi)
r2 = gf(6, pi)

相关文章

网友评论

      本文标题:Python的学习

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