|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
|
|
Get inside! Sample the range of functionality easily built with JMSL Library for Time Series Data Analysis, Heat Maps, Portfolio Optimization, Monte Carlo Simulation, Stock Price Charting and more. Download Now! |
|
#1
|
||||
|
||||
|
Declaring Python class variables
Playing around with Python for the first time and have a question about classes - how to you declare class variables? I know you don't have to but I'd like to to make the class easier to read.
In PHP, for example, I might do this; Code:
class Test {
var $message; // declare variable
function Test ($message) {
$this->message=$message;
}
function get() {
return $this->message;
}
}
In Python I've got as far as; Code:
class Test:
def __init__(self,message):
self.message=message
def get(self):
return self.message
I'd like to be able to declare the message variable to make it readable. One other question; when declaring class methods, do I always have to make the first parameter "self"? And why is it Python does this in the first place? Seems a little odd compared to methods in Java or PHP for example. Many thanks. |
|
#2
|
||||
|
||||
|
>> how to you declare class variables?
You mean instance variables (data members)? Like this: Code:
class Test:
my_attr = '';
def __init__(self,message):
self.message=message
def get(self):
return self.message
Or you can just use self.message like you showed and the instance variable will spring into existence. To define private variables, add 2 leading underscores (e.g. __myvar) and Python will mangle it into _classname__myvar. Data hiding in this case is not strictly enforced as in Java (since you can access it using '_classname__myvar' - it's more of a 'contractual agreement' basis) >> when declaring class methods, do I always have to make the first parameter "self"? And why is it Python does this in the first place? Consider an object x of class Test (which you defined above). Typically, from outside the class, you'd call the get() method of x like so: Code:
msg = x.get(); What Python does is translate it into Code:
msg = Test.get(x); Why the parameter is called 'self' is a matter of convention (meaning you can use something like 'pinkgoblin' instead of 'self', but it's good to follow the convention to prevent confusing others) |
|
#3
|
||||
|
||||
|
Many thanks. Clears up alot.
|
![]() |
| Viewing: Dev Shed Forums > Programming Languages > Python Programming > Declaring Python class variables |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|