[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

newb question about @property

Ned Batchelder wrote:
> On 9/30/17 7:18 PM, Bill wrote:
>> Ned Batchelder wrote:
>>> On 9/30/17 5:47 PM, Bill wrote:
>>>> I spent a few hours experimenting with @property. To my mind it 
>>>> seems like it would be preferable to just define (override) 
>>>> instance methods __get__(), __set__(), and possibly __del__(), as 
>>>> desired, as I could easily provide them with "ideal" customization. 
>>>> Am I overlooking something?
>>> It would be easier to comment if you showed the two options. One 
>>> with @property, and one with __get__ etc.
>>> A downside to __get__ is that you need to create a class with those 
>>> methods, and then instantiate that class as an attribute in your 
>>> real class, whereas @property can be used without a lot of rigamarole.
>>> --Ned.
>> I am basically mimmicking what I see at (the very bottom of) this page:
>> https://www.programiz.com/python-programming/property
> Can you show us the code you are using it to mimic that?
> --Ned.

Here it is, Ned. It's my first attempt at using classes in Python.
I still have to learn how to incorporate datetime appropriately!  :)

import datetime

# object oriented example class Employee(object):
     ''' This class will abstract an employee. Class date members name, a 
string birthday, a date object address, a string position It also has a 
static data member for the number of employees. ''' num_employees =0 # class data item @classmethod def get_num_employees(cls):
         return Employee.num_employees

     def __init__(self, name, birthdate, address, position):
         Employee.num_employees +=1 self.name = name
         self.birthdate = birthdate
         self.address = address
         self.position = position

     @property def address(self):
         print("**Hi from address-getter**")
         return self._address

     @address.setter def address(self, value):
         print("*****Hi, from address setter()!")
         self._address = value

     def __del__(self):
         print("******* Hi, from __del__()")
         ##Employee.num_employees -= 1 def __str__(self):
         return 'Name: {}, Born: {} \nAddress: {} \nPosition: {} \n'.\

class SalesPerson(Employee):
     def __init__(self, name, bdate, addr):
         super().__init__(name, bdate, addr,"Salesperson")

def main():
         emp1 = Employee("Sam","4/30/1970","212 Elm","Programmer")
         emp2 = SalesPerson("Gene","5/1/79","414 Maple")
         ## Note: learn to use datetime.date--> str print(emp1)
         emp1.address ="230 Main Street" # call setter? print(emp1)
         print("Number of employees", Employee.get_num_employees())

main()#call main()