Javascript`the` vs Python`self`构造函数

时间:2017-08-08 18:04:54

标签: javascript python object constructor

Javascript构造函数+创建对象示例

//Constructor
function Course(title,instructor,level,published,views){
    this.title = title;
    this.instructor = instructor;
    this.level = level;
    this.published = published;
    this.views = views;
    this.updateViews = function() {
        return ++this.views;
    }
}

//Create Objects
var a = new Course("A title", "A instructor", 1, true, 0);
var b = new Course("B title", "B instructor", 1, true, 123456);

//Log out objects properties and methods
console.log(a.title);  // "A Title"
console.log(b.updateViews()); // "123457"

python相当于什么? (构造函数/或类+创建对象实例+注销属性和方法?)

来自python的self与来自Javascript的this之间是否存在差异?

2 个答案:

答案 0 :(得分:4)

这是一个python翻译:

class Course:

    def __init__(self,title,instructor,level,published,views)

        self.title = title
        self.instructor = instructor
        self.level = level
        self.published = published
        self.views = views

    def update_views(self):
        return self.views += 1

您必须声明一个类,然后按如下方式初始化该类:

course = Course("title","instructor","level","published",0)

一些值得注意的差异是self不是隐式可用的,但实际上是类的所有实例函数的必需参数。但是,有关更多信息,请参阅 the documentation 了解python类。

修改

python3.7开始,我觉得有必要证明新引入的dataclasses是写这种类的最pythonic方式,可能对你未来的python开发者有所帮助。

from dataclasses import dataclass

@dataclass
class Course:

     title: str 
     instructor: str 
     level: str 
     published: bool
     views: int 

     def update_views(self):
         return self.views += 1 

答案 1 :(得分:1)

现在修复了python解决方案的一些错误

// Define common constants for stabiliy.
if (!defined("STONEHENGE_PLUGIN_VERSION"))      define("STONEHENGE_PLUGIN_VERSION", "2.0.0");
if (!defined("STONEHENGE_PLUGIN_DIR_PATH"))     define("STONEHENGE_PLUGIN_DIR_PATH", plugins_url('' , __FILE__));

// TO DO: Add MultiSite compatibility for network Activation.
// Current version only works if activated per blog.

// Let's load the language files.
load_plugin_textdomain('stonehenge', false, basename( dirname( __FILE__ ) ) . '/languages/' );

Class Stonehenge_Fields {
    // Add additional Arrays to dynamically create more inputs. That's it!
    static $stonehenge_fields = array(
        'Facebook' => array(            
            'Page URL'  => 'text',                  
            'App ID'    => 'text',      
            'Admin ID'  => 'text',              
        ),  
/*      'Section' => array(         
            'Field 1'   => 'text',                  
            'Field 2'   => 'textarea',      
            'Field 3'   => 'checkbox',              
        ),  
*/
    );

}

// TO DO: Add a hook to remove all option fields upon deactivation of the Plugin.
//delete_option('stonehenge_website_name');


// Call stonehenge_menu function to load Admin Menu in the Dashboard.
add_action( 'admin_menu', 'stonehenge_menu_page' );

// Let's create WordPress Admin Menu
function stonehenge_menu_page(){
  $page_title = __('Stonehenge Custom Fields & Data Settings', 'stonehenge'); 
  $menu_title = __('Stonehenge Fields', 'stonehenge');
  $capability = 'manage_options';
  $menu_slug  = 'stonehenge';
  $function   = 'stonehenge_options_page';
  $icon_url   = 'dashicons-admin-plugins';
  $position   = 99;
  add_menu_page( $page_title, $menu_title, $capability, $menu_slug, $function, $icon_url, $position );
}

function stonehenge_register_settings() {
// Let's create and register the Sections.
   $sections = Stonehenge_Fields::$stonehenge_fields;
    foreach ($sections as $section => $key) {
        add_settings_section($section, $section, 'stonehenge_callback', __FILE__ );

// Let's create and register the input fields in options.php (acutal input fields are created in function stonehenge_options_page. )
        foreach ($key as $name => $type)    {
            $prefix     = 'stonehenge';         
            $field      = str_replace(' ', '_', strtolower( $prefix.'_'.$section.'_'.$name ) );
            $label      = ucfirst($section.' '.$name);
            $value      = get_option($prefix.'_'.$section.'_'.$name);
            $input      = '<input type="' .$type. '"name="'.$field.'" id="'.$field.'" value="'.$value.'"> ';
            $label_for      = '<label for='.$field.'>' . $label . '</label>';
            add_option($field, $value);
            register_setting('stonehenge_options_group',$field, 'stonehenge_callback');
        }
    }
}
add_action( 'admin_init', 'stonehenge_register_settings' );

// Let's create the Main Page.
function stonehenge_options_page()
{
?>
  <div class="wrap">
  <h1><?php _e('Stonehenge Custom Fields & Data Settings', 'stonehenge'); ?></h1>
  <form method="post" action="options.php">
  <?php settings_fields( 'stonehenge_options_group' ); ?>
  <table cellspacing="4" cellpadding"3">

  <?php
//Let's create the Sections
    $sections = Stonehenge_Fields::$stonehenge_fields;
    foreach ($sections as $section => $key) {
        $section_label = ucfirst($section);
        echo ('<th scope="row" colspan="2" align="left"><br><h2>'.$section_label.' '.__('Settings','stonehenge').'</h2></th>');

// Let's create the actual Labels and input Fields 
        foreach ($key as $name => $type)    {
            $prefix     = 'stonehenge';         
            $field      = str_replace(' ', '_', strtolower( $prefix.'_'.$section.'_'.$name ) );
            $label      = ucfirst($section.' '.$name);
            $value      = get_option($field);
// TO DO: Create switch arguments for different input types, such as Checkbox, Radio, Textarea, Password, etc.
            $input      = '<input type="' .$type. '"name="'.$field.'" id="'.$field.'" value="'.$value.'"> ';
// Using <label for> Makes it clickable. Very handy!
            $label_for      = '<label for='.$field.'>' . $label . '</label>';
            ?><tr><th scope="row" align="left"><?php echo $label_for; ?></th><td><?php echo $input; ?></td></tr><?php 
        }
    }?>
  </table>
  <?php  submit_button(); ?>
  </form>
  </div>
<?php
}

// That's all Folks! :-)

?>  

打印结果

  

标题

     

123457

使用#Constructors class Course: def __init__(self,title,instructor,level,published,views): self.propTitle = title self.propInstructor = instructor self.propLevel = level self.propPublished = published self.propViews = views def update_views(self): self.propViews += 1 return self.propViews # Create objects courseA = Course("A title", "A instructor", 1, True, 0) courseB = Course("B title", "B instructor", 1, True, 123456) # Print object property and use object method print(courseA.propTitle) print(courseB.update_views()) 输出,print(courseB.update_views),使用<bound method Course.update_views of <__main__.Course object at 0x7f9f79978908>>