2017-08-03 34 views
-2

我正在學習python食譜。 我試圖執行下面的代碼,這是從蟒食譜第8章。 此代碼是有關類在Python中製作類的屬性

class Person: 
    def __init__(self, first_name): 
     self.first_name=first_name 

    #getter function 
    #property 
    def first_name(self): 
     return self._first_name 

    #settier function 
    def first_name(self, value): 
     print(value, isinstance (value,str)) 
     if not isinstance(value, str): 
      raise TypeError("expected a string") 
     self._first_name=value 

    #deleter function 
    def first_name(self): 
     raise AttributeError("can not delete attribute") 

    c=Person('PETTER') 
    c.first_name(42) 

的特性使得下課後,我做了實例,我進入上目的錯誤值。

我希望我得到了TypeError(預期是一個字符串)。 但我沒有。 我的代碼的哪些部分應該更改?

+1

我投票細節關閉這個問題作爲題外話b因爲SO不是SolveMyExerciseForMe.com –

回答

2

我想你忘記了一些作品,特別是:

  1. @property第一def first_name(self):

  2. @first_name.setter上述def first_name(self, value):

  3. @first_name.deleter第二def first_name(self):

上方上面
+0

謝謝!我解決了它 –

0

下面的代碼會給你你所期望的錯誤。

兩個主要問題:

  1. 你在你的__init__self.first_name = first_name。這最終會覆蓋功能first_name。你的意思是self._first_name = ...
  2. 您定義了相同的功能三次(first_name)。 Python沒有函數重載,所以你不能這樣做。我相信最後的定義會獲勝。下面我評論了我認爲你實際上不打算打電話的兩個功能。
  3. 你有一個縮進錯誤......你最後兩行可能根本沒有被執行,因爲它們在你的類定義中。

「工作」代碼:

class Person: 
    def __init__(self, first_name): 
     self._first_name = first_name 

    #getter function 
    #property 
    # def first_name(self): 
    #  return self._first_name 

    #settier function 
    def first_name(self, value): 
     print(value, isinstance (value,str)) 
     if not isinstance(value, str): 
      raise TypeError("expected a string") 
     self._first_name=value 

    #deleter function 
    # def first_name(self): 
    #  raise AttributeError("can not delete attribute") 

c = Person('PETTER') 
c.first_name(42) 

編輯

至於其他的答案指出,根據你的問題的情況下,你可能要做出first_name實際屬性通過@property裝修。這可能是使代碼正常工作的更好方法,但希望這可以幫助您瞭解現有代碼中發生的情況。

0

你缺少裝飾功能與@property@Setter

class Person: 
    def __init__(self, first_name): 
     self.first_name=first_name 


    @property 
    def first_name(self): 
     return self._first_name 

    @first_name.setter 
    def first_name(self, value): 
     print(value, isinstance (value,str)) 
     if not isinstance(value, str): 
      raise TypeError("expected a string") 
     self._first_name=value 

財產exapmle

class Temp: 

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

    @property 
    def x(self): 
     return self.__x 

    @x.setter 
    def x(self, x): 
     self.__x = x 

property in python

+0

謝謝!我解決它! –

+0

@junghyemin wlcm – Kallz