首页 > 编程 > Python > 正文

不归路系列:Python入门之旅-一定要注意缩进!!!(推荐)

2019-11-25 13:00:58
字体:
来源:转载
供稿:网友

因为工作(懒惰),几年了,断断续续学习又半途而废了一个又一个技能。试着开始用博客记录学习过程中的问题和解决方式,以便激励自己和顺便万一帮助了别人呢。

最近面向对象写了个Python类,到访问限制(私有属性)时竟然报错,好多天百思不得其姐,没啥破绽啊!代码如下,可就是报错!(后面有报错截图)

class Person(object):   def run(self):    print("run")   def eat(self,food):    print("eat " + food)   def say(self):    print("My name is %s,I am %d years old" % (self.name,self.age))    # 构造函数,创建对象时默认的初始化  def __init__(self,name,age,height,weight,money):    self.name = name    self.age = age    self.height = height    self.weight = weight    self.__money = money #实际上是_Person__money    print("哈喽!我是%s,我今年%d岁了。目前存款%f" %(self.name,self.age,self.__money))    # 想要内部属性不被直接外部访问,属性前加__,就变成了私有属性private    self.__money = 100     # 私有属性需要定义get、set方法来访问和赋值    def setMoney(self,money):      if(money < 0):        self.__money = 0      else:        self.__money = money     def getMoney(self):      return self.__money person = Person("小明", 5, 120, 28,93.1) # 属性可直接被访问person.age = 10print(person.age) # 私有属性不可直接被访问或赋值,因为解释器把__money变成了_Person__money(可以用这个访问到私有属性的money,但是强烈建议不要),以下2行会报错# person.money = 10# print(person.__money) # 可以调用内部方法访问和赋值print(person.getMoney())person.setMoney(-10)print(person.getMoney())

Excuse me?!咋个就没有,那不上面大大摆着俩内部方法嘛!

昨天看着看着突然迸发了个小火星子,想起来缩进不对了,如图:

把两个方法减一个缩进,就算是出来了,是类的方法,和__init__并列了,自然就正确了。

class Person(object):   def run(self):    print("run")   def eat(self,food):    print("eat " + food)   def say(self):    print("My name is %s,I am %d years old" % (self.name,self.age))    # 构造函数,创建对象时默认的初始化  def __init__(self,name,age,height,weight,money):    self.name = name    self.age = age    self.height = height    self.weight = weight    self.__money = money #实际上是_Person__money    print("哈喽!我是%s,我今年%d岁了。目前存款%f" %(self.name,self.age,self.__money))    # 想要内部属性不被直接外部访问,属性前加__,就变成了私有属性private    self.__money = 100   # 私有属性需要定义get、set方法来访问和赋值  def setMoney(self, money):    if (money < 0):      self.__money = 0    else:      self.__money = money   def getMoney(self):    return self.__money person = Person("小明", 5, 120, 28,93.1) # 属性可直接被访问person.age = 10print(person.age) # 私有属性不可直接被访问或赋值,因为解释器把__money变成了_Person__money(可以用这个访问到私有属性的money,但是强烈建议不要),以下2行会报错# person.money = 10# print(person.__money) # 可以调用内部方法访问和赋值print(person.getMoney())person.setMoney(-10)print(person.getMoney())

总结下:一定要细心!细心!!再细心!!!

注意缩进

注意缩进

注意缩进

以上所述是小编给大家介绍的Python入门一定要注意缩进详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持!

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表