Python在类中获取变量 [英] Python getting a variable in a class

查看:530
本文介绍了Python在类中获取变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在正在学习一种python语言,但是我想以OOP风格进行编程.很抱歉我的问题,但是在我的书和视频教程中,我找不到答案.我知道有一种更简便的方法来获取没有方法的数字...但是我想在一个类中完成它;)

I'm learning right now a python language but I would like to programm in OOP style. Sorry for my questions but in my book and a video tutorial I couldn't find an answer. I know there is easer way to get a number without a method... but I would like to do it in a class ;)

我想从用户那里读取一个号码.

I would like to read a number from a user.

如何编写一种从用户那里获取数字并将其放回构造函数的方法?

How to write a method that take a number from a user and put it back to a constructor?

我尝试过这个,但是效果不好:(

I tried this one but it isn't good :(

 class example:
      def __init__(self, number):
          self.number = number

      def read(self, a):
           self.a = float(input('Give me a number) '))
           return a


 exampleNumber = example (read())

推荐答案

正如其他人建议的那样,将输入分隔为独立函数是一种不错的方法,但是如果您确实想将输入保留在类中,则可以使用classmethod提供备用构造函数:

As others have suggested separating the input to a standalone function would be a good way to go, but if you really want to keep the input in the class you can use a classmethod to provide an alternate constructor:

class Example:
    def __init__(self, number):
        self.number = number

    @classmethod
    def from_input(cls):
        a = float(input('Give me a number: '))
        return cls(a)

exampleNumber = Example.from_input()
print("The number is %i" % exampleNumber.number)

通常认为这是为具有不同不兼容参数的类提供多个构造函数的最Pythonic方式.比较例如dict.fromkeys(...)

This is often considered the most Pythonic way to provide multiple constructors for a class with different incompatible parameters. Compare for example dict.fromkeys(...)

顺便说一句,代码中的print表示您正在使用Python2.x.如果是这样,您应该使用raw_input()读取值,或者更好地升级到Python 3.x.

BTW, the print in your code implies you are using Python 2.x. If so you should use raw_input() to read values, or better upgrade to Python 3.x.

这篇关于Python在类中获取变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆