簡體   English   中英

如何在 python 中打印屬性。 它是打印位置。 但我需要打印“25”

[英]How to print attributes in python. it is printing location. but i need to print ''25"

它應該打印一個數字,而不是位置。

a=25
class me:
    def it(a):
        print(a)
m=me()
m.it()

我應該得到 25,但我得到 - <__main__.me object at 0x7f98cb648b70>

這應該是類,必須在 class 內,我定義設置/獲取方法

class me:

    def __init__(self, a):
        self.a = a      

    def set_a(self, v):
        self.a = v

    def get_a(self):
        return self.a

m = me(5)

m.get_a()
m.set_a(12)
m.get_a()

Output

5
12

在您的情況下it的方法被視為instance methodinstance method的第一個參數始終是實例( self )。 因此,當您執行print(a)時,它會打印實例的位置,而不是打印變量a的值。

您可以it方法聲明為 static 如下所示

a=25
class me:
    @staticmethod
    def it():
        print(a)
m=me()
m.it()

或者你可以做

a=25
class me:
    def it(self):
        print(a)
m=me()
m.it()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM