python取变量地址,Python在类中获取变量

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())

解决方案

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)

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

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值